只是为了发布 Fluent 方法来实现这一点。
public class MyDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Item>.Ignore(c => c.UISize);
}
}
取决于您的用例以及其他配置对象的存储位置。您想要实现的目标可以通过多种方式完成。但是如果一个属性被设置为被忽略。显然不会在查询 DbSets 时指定。
EF Core 需要一个空的构造函数,尽管它不必是公共的。
- 对被忽略的属性使用访问方法
public class Person
{
// It doesn't have to be public though. So you can still put some encapsulation
// on your application logic.
protected Person()
{
// EF Core will use this.
// But since name only exists in database. Shoesize won't be set.
}
// Descriptive constructor to use for instantiating outside of the Database logic.
public Person(string name)
{
Name = name;
ShoeSize = 1 // some value prefetched from configuration object ?
}
public string Name { get; private set; }
public int ShoeSize { get; private set; }
public void SpecifyShoeSize(int shoeSize)
{
ShoeSize = shoeSize;
}
}
public MyDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>.Ignore(person => person.ShoeSize);
}
}
如果你想完全确定你不会弄乱该类的其他消费者
- 使用继承的扩展实体类。注意:此实体未在任何数据库集中映射或使用。
public PersonwithShoeSize() : Person
{
public int ShoeSize {get; set;}
public PersonwithShoeSize(Person person, int shoeSize): base(person.Name)
{
ShoeSize = shoeSize;
}
}
// you can ignore entity classes entirely through the fluid api as well
public class MyDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Ignore<PersonWithShoeSize>();
}
}
例如链接到文章
https://www.learnentityframeworkcore.com/configuration/fluent-api/ignore-method
-------------- 更新 -------- -----
对于执行此操作的自动方式,在获取数据后。
你可以像你提到的那样,尝试使用价值转换器
.HasConversion(
fromprovider: ()=> { /* since property is not mapped, this line doesn't matter */ },
toprovider()=>{ /* set the not mapped property here */ })
我个人并不是这种方法的忠实拥护者,因为您必须将其他数据存储注入 DbContext 才能被允许这样做。
如果您使用的是 EF Core 5,更简洁的方法是使用 EF Core 拦截器并标记您的查询,以便拦截器可以接收它。然后你就可以使用真正的 DI 并有足够的逻辑分离出来。
EF Core 拦截器链接:
https://docs.microsoft.com/en-us/ef/core/logging-events-diagnostics/interceptors