覆盖派生类中的NotMapped属性

时间:2017-09-19 02:33:01

标签: c# entity-framework ef-code-first

我正在开发基于EF Code-First的应用程序。我有一个由几十个类继承的基类,每个类代表数据库中的实体。基类具有[NotMapped]属性的属性,对于所有派生类,该属性最初也必须为[NotMapped]

public class BaseEntity
{
    [NotMapped]
    public string Message { get; set; }
}

我遇到了一个实体,其列名与该属性名称完全相同,但由于从父级继承了[NotMapped]属性,因此该值不会存储在数据库中。

public class InheritedEntity : BaseEntity
{
    public string Message { get; set; } // This is what I want mapped
}

有没有办法通过DataAnnotations或FluentAPI覆盖该类的NotMapped行为?我已尝试设置[Column()],但它无法正常工作。

1 个答案:

答案 0 :(得分:0)

您需要创建一个与NotMapped相同的新属性。

#N/A
将ff应用于您的modelBuilder配置:
NotMappedPropertyAttributeConvention

首先,创建自定义属性。

ConventionTypeConfiguration Ignore(PropertyInfo propertyInfo)

然后,创建一个PropertyAttributeConvention


public class CustomNotMappedAttribute : Attribute
{
    public CustomNotMappedAttribute()
    {
        this.Ignore = true;
    }
    public bool Ignore { get; set; }
}

然后,将其添加到配置约定中


public class CustomNotMappedPropertyAttributeConvention : PropertyAttributeConfigurationConvention
{
    public override void Apply(PropertyInfo memberInfo, ConventionTypeConfiguration configuration, CustomNotMappedAttribute attribute)
    {
        if (attribute.Ignore)
        {
            configuration.Ignore(memberInfo);
        }
    }
}

您在entitybase中的属性应装饰为:


protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Add(new CustomNotMappedPropertyAttributeConvention());
}
而非
[CustomNotMapped]
[NotMapped]

你去了。除了以 public class BaseEntity { [CustomNotMapped] public virtual string Message { get; set; } } public class InheritedEntity : BaseEntity { [CustomNotMapped(Ignore = false)] public override string Message { get; set; } }

装饰的消息属性外,您在BaseEntity中的message属性将被忽略。
相关问题