【问题标题】:Override NotMapped attribute in derived class覆盖派生类中的 NotMapped 属性
【发布时间】:2017-09-19 02:33:00
【问题描述】:

我正在开发一个基于 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()],但它不起作用。

【问题讨论】:

  • 我没有想到一个简单的解决方案,即在派生类中重命名“消息”,例如到“StatusMessage”并使用 [Column] 属性将其映射到“消息”列。这对我有用,所以现在一切都很好。
  • ^ 这应该是一个答案。
  • 顺便说一句,在您当前的代码中,Message 应该是一个覆盖。
  • @Usman,这也是我能找到解决此问题的唯一方法。你应该把它作为你自己问题的答案。

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


【解决方案1】:

您需要创建一个新属性来执行 NotMapped 的操作。

NotMappedPropertyAttributeConvention
将 ff 应用于您的模型构建器配置:
ConventionTypeConfiguration Ignore(PropertyInfo propertyInfo)

首先,创建自定义属性。


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

然后,创建一个 PropertyAttributeConvention


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

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


protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Add(new CustomNotMappedPropertyAttributeConvention());
}

您在 entitybase 中的属性应使用:

[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 属性将被忽略,除了那些用 [CustomNotMapped(Ignore = false)] 装饰的属性

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 2012-06-02
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多