简体   繁体   English

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

[英]EF 6.1 Fluent API: Ignore property of the base class

I have a base class for all entities: 我对所有实体都有一个基类:

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

public class SomeEntity : BaseClass
{
    ...
}

I want to ignore this property in some cases. 在某些情况下,我想忽略此属性。 Could I do in the OnModelCreating method something like this: 我可以在OnModelCreating方法中执行以下操作:

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Properties<int>()
                    .Where(p => p.Name == "SomeProperty")
                    .Ignore();
}

?

You could try: 您可以尝试:

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

It will cause SomeProperty not to be mapped to SomeEntity . 这将导致SomeProperty不会映射到SomeEntity

EDIT: If this property should never be mapped to database you can add NotMapped annotation in your BaseClass : 编辑:如果此属性永远不应映射到数据库,则可以在BaseClass添加NotMapped批注:

public class BaseClass
{
    [NotMapped]
    public int SomeProperty {get; set;}
}

This will be the same as ignoring this property in all extending classes. 这与在所有扩展类中忽略此属性相同。

A late entry here - but in case it's useful... 此处输入较晚-但如果有用的话...

Having recently encountered similar requirements, I went with this:- 最近遇到类似的要求,我这样做了:-

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder mb)
    {
        mb.Types<EntityBase>()
          .Configure(config => config.Ignore(x => x.SomeBaseClassPropertyToIgnore));
    }
}

This will apply the given configuration to all entity types that inherit from EntityBase. 这会将给定的配置应用于从EntityBase继承的所有实体类型。 The same technique can be used to configure entity types based on an interface they implement (probably a better approach anyway). 可以使用相同的技术基于它们实现的接口来配置实体类型(无论如何可能是一种更好的方法)。

Advantages are:- 优点是:

  • No need to write and maintain the same config code for multiple concrete entities. 无需为多个具体实体编写和维护相同的配置代码。
  • No need for [NotMapped] attribute, which is less flexible and adds potentially unwanted dependencies. 不需要[NotMapped]属性,该属性不太灵活,并添加了可能不需要的依赖项。

Note that the targeted types can be filtered further if necessary:- 请注意,如有必要,可以进一步过滤目标类型:

protected override void OnModelCreating(DbModelBuilder mb)
{
    mb.Types<EntityBase>().Where(t => t != typeof(SpecialExceptionEntity)).Configure(...);
}

Refs:- 参考文献: -

https://msdn.microsoft.com/en-us/library/dn235653(v=vs.113).aspx https://msdn.microsoft.com/en-us/library/dn235653(v=vs.113).aspx

https://msdn.microsoft.com/en-us/library/dn323206(v=vs.113).aspx https://msdn.microsoft.com/en-us/library/dn323206(v=vs.113).aspx

Could you override it? 您可以覆盖它吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM