我有以下基类。
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; }
}
它是所有实体的基类。
例如,
public class Task : BaseEntity
{
public virtual string Name {get;set;}
}
我有一个初始化程序,
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 => b.IsDeleted).Not.Nullable().Default("0");
});
return p;
}
}
当然在数据库中 - CreateDate是datetime,null,而CreatedBy是nvarchar(255)。
如何配置此AutoMapper以将这些映射从基类到所有子类?
答案 0 :(得分:3)
您无法覆盖基类的映射,因为实际上并未创建该映射。如果要继续使用Automapper,可以创建约定
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...
}
}
}
}