Fluent NHibernate自动映射基类重写



我有以下基类。

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以获取从基类到所有子类的这些映射?

不能覆盖基类的映射,因为实际上从来没有创建过该映射。如果你想继续使用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...
            }
        }
    }
}

最新更新