C# 重写派生类中的NotMapped属性
我正在开发一个基于EF代码优先的应用程序。我有一个由几十个类继承的基类,每个类代表数据库中的实体。基类有一个具有C# 重写派生类中的NotMapped属性,c#,entity-framework,ef-code-first,C#,Entity Framework,Ef Code First,我正在开发一个基于EF代码优先的应用程序。我有一个由几十个类继承的基类,每个类代表数据库中的实体。基类有一个具有[NotMapped]属性的属性,对于所有派生类,该属性最初也必须是[NotMapped] public class BaseEntity { [NotMapped] public string Message { get; set; } } 我遇到了一个列名与该属性名完全相同的实体,但由于从父级继承了[NotMapped]属性,该值不会存储在数据库中 public
[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()]
,但它不起作用。您需要创建一个新属性,该属性执行NotMapped所做的操作
NotMappedPropertyAttributeConvention
将ff应用于modelBuilder配置:
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]
而不是
好了。BaseEntity中的message属性将被忽略,除了那些用
[CustomNotMapped(ignore=false)]修饰的属性之外。
您需要创建一个新属性来执行NotMapped所做的操作
NotMappedPropertyAttributeConvention
将ff应用于modelBuilder配置:
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]
而不是
好了。BaseEntity中的message属性将被忽略,除了那些用
[CustomNotMapping(ignore=false)]修饰的属性之外。
我没有想到一个简单的解决方案,即在派生类中将“message”重命名为“StatusMessage”,并使用[column]属性将其映射到“message”列。这对我来说很有效,所以现在一切都很好。^这应该是一个答案。顺便说一句,在你当前的代码中,Message
应该是一个覆盖项。@Usman,这也是我唯一能找到的解决方法。您应该把它作为您自己问题的答案。我没有想到一个简单的解决方案,即在派生类中重命名“Message”,例如重命名为“StatusMessage”,并使用[column]属性将其映射到“Message”列。这对我来说很有效,所以现在一切都很好。^这应该是一个答案。顺便说一句,在你当前的代码中,Message
应该是一个覆盖项。@Usman,这也是我唯一能找到的解决方法。你应该把它作为你自己问题的答案。