I have the following base class.
public abstract class BaseEntity
{
public virtual long Id { get; set; }
public virtual DateTime CreateDate { get; set; }
public virtual DateTime? UpdateDate { get; set; }
public virtual bool IsDeleted { get; set; }
public virtual string CreatedBy { get; set; }
}
And it's a base class for all entities.
For example,
public class Task : BaseEntity
{
public virtual string Name {get;set;}
}
I have an initializer,
public class Initializer
{
public static AutoPersistenceModel MapEntities()
{
var p = AutoMap
.AssemblyOf<User>(new MyDefaultAutomappingConfiguration())
.IgnoreBase<BaseEntity>()
.UseOverridesFromAssemblyOf<Initializer>()
.Override<BaseEntity>(map =>
{
map.Map(b => b.CreateDate).Not.Nullable().Not.Update();
map.Map(b => b.CreatedBy).Not.Nullable().Length(100);
map.Map(b => b.ModifiedBy).Length(100);
map.Map(b => b.DeletedBy).Length(100);
map.Map(b =&开发者_如何学Gogt; b.IsDeleted).Not.Nullable().Default("0");
});
return p;
}
}
And of course in the database - CreateDate is datetime, null, and CreatedBy is nvarchar(255).
How can I configure this AutoMapper to get these mappings from the base class to all child classes?
You can't override a mapping for a base class since that mapping doesn't actually ever get created. If you want to continue using the Automapper you can create a convention
public class BaseEntityPropertiesConvention : IPropertyConvention
{
public void Apply(IPropertyInstance instance)
{
if (instance.EntityType.IsSubclassOf(typeof(BaseEntity)))
{
switch instance.Name
{
case "CreatedDate":
instance.Not.Nullable().Not.Update();
break;
case "CreatedBy":
instance.Not.Nullable().Length(100);
break;
//etc...
}
}
}
}
精彩评论