C# EF 6.1 Fluent API:忽略基类的属性

C# EF 6.1 Fluent API:忽略基类的属性,c#,ef-code-first,C#,Ef Code First,我有一个适用于所有实体的基类: public class BaseClass { public int SomeProperty {get; set;} } public class SomeEntity : BaseClass { ... } 在某些情况下,我想忽略此属性。我可以在OnModelCreating方法中执行以下操作: public class MyContext : DbContext { protected override void OnModel

我有一个适用于所有实体的基类:

public class BaseClass
{
    public int SomeProperty {get; set;}
}

public class SomeEntity : BaseClass
{
    ...
}
在某些情况下,我想忽略此属性。我可以在OnModelCreating方法中执行以下操作:

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Properties<int>()
                    .Where(p => p.Name == "SomeProperty")
                    .Ignore();
}
公共类MyContext:DbContext
{
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
modelBuilder.Properties()
.Where(p=>p.Name==“SomeProperty”)
.Ignore();
}

您可以尝试:

modelBuilder.Entity<SomeEntity>().Ignore(p => p.SomeProperty);

这与在所有扩展类中忽略此属性相同。

此处是一个延迟条目-但如果有用

由于最近遇到了类似的要求,我采用了以下方法:-

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder mb)
    {
        mb.Types<EntityBase>()
          .Configure(config => config.Ignore(x => x.SomeBaseClassPropertyToIgnore));
    }
}
公共类MyContext:DbContext
{
模型创建时受保护的覆盖无效(DbModelBuilder mb)
{
mb.Types()
.Configure(config=>config.Ignore(x=>x.SomeBaseClassPropertyToIgore));
}
}
这将把给定的配置应用于从EntityBase继承的所有实体类型。同样的技术可以用于根据实体类型实现的接口配置实体类型(无论如何,这可能是更好的方法)

优点是:-

  • 无需为多个具体实体编写和维护相同的配置代码
  • 不需要[NotMapped]属性,该属性灵活性较低,并添加了可能不需要的依赖项
请注意,如有必要,可以进一步筛选目标类型:-

protected override void OnModelCreating(DbModelBuilder mb)
{
    mb.Types<EntityBase>().Where(t => t != typeof(SpecialExceptionEntity)).Configure(...);
}
模型创建时受保护的覆盖无效(DbModelBuilder mb)
{
mb.Types().Where(t=>t!=typeof(SpecialExceptionEntity)).Configure(…);
}
参考文献:-

你能覆盖它吗

public class SomeEntity : BaseClass
{    
    [NotMapped]
    public override int SomeProperty { get; set; }
    ...
}

我怀疑这会破坏Liskov的替代原则。如何?我只是在寻找一些基于外部条件的EF行为最简单的方法。我不想在继承中移除属性。我所说的是,应该考虑从实体框架中移除属性的时间和时间,因为它会破坏LSP。实际上是正确的方法。我知道这种构造。但是我有很多实体,1)我不想为每个实体添加它2)当我创建新实体时,我需要添加另一个实体。
public class SomeEntity : BaseClass
{    
    [NotMapped]
    public override int SomeProperty { get; set; }
    ...
}