Reputation: 51
I'm working on an EF Code-First based application. I have a base class inherited by dozens of classes, each representing entities in database. The base class has a property with [NotMapped]
attribute, that was originally required to be [NotMapped]
for all derived classes as well.
public class BaseEntity
{
[NotMapped]
public string Message { get; set; }
}
I've come across an entity having column name exactly as that property name, but just due to inheriting [NotMapped]
attribute from the parent, the value doesn't get stored in database.
public class InheritedEntity : BaseEntity
{
public string Message { get; set; } // This is what I want mapped
}
Is there any way to override the NotMapped
behaviour just for that class, either through DataAnnotations or FluentAPI? I've tried setting [Column()]
but it doesn't work.
Upvotes: 2
Views: 1349
Reputation: 5248
You need to create a new attribute that does what NotMapped do.
NotMappedPropertyAttributeConvention
Applies the ff to your modelBuilder configuration: ConventionTypeConfiguration Ignore(PropertyInfo propertyInfo)
First, create custom attribute.
public class CustomNotMappedAttribute : Attribute
{
public CustomNotMappedAttribute()
{
this.Ignore = true;
}
public bool Ignore { get; set; }
}
Then, create a PropertyAttributeConvention
public class CustomNotMappedPropertyAttributeConvention : PropertyAttributeConfigurationConvention
{
public override void Apply(PropertyInfo memberInfo, ConventionTypeConfiguration configuration, CustomNotMappedAttribute attribute)
{
if (attribute.Ignore)
{
configuration.Ignore(memberInfo);
}
}
}
Then, add it to the configuration conventions
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add(new CustomNotMappedPropertyAttributeConvention());
}
Your property in entitybase should be decorated with:
[CustomNotMapped]
instead of [NotMapped]
public class BaseEntity
{
[CustomNotMapped]
public virtual string Message { get; set; }
}
public class InheritedEntity : BaseEntity
{
[CustomNotMapped(Ignore = false)]
public override string Message { get; set; }
}
There you go. Your message property in your BaseEntity will be ignore except to those decorated with [CustomNotMapped(Ignore = false)]
Upvotes: 2