简体   繁体   English

Fluent NHibernate 自动映射基础 class 覆盖

[英]Fluent NHibernate automap base class overrides

I have the following base class.我有以下基础 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.它是所有实体的基础 class。

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 => b.IsDeleted).Not.Nullable().Default("0");
            });
        return p;
    }
}

And of course in the database - CreateDate is datetime, null, and CreatedBy is nvarchar(255).当然在数据库中 - CreateDate 是日期时间,null,CreatedBy 是 nvarchar(255)。

How can I configure this AutoMapper to get these mappings from the base class to all child classes?如何配置此 AutoMapper 以获取从基础 class 到所有子类的这些映射?

You can't override a mapping for a base class since that mapping doesn't actually ever get created.您不能覆盖基本 class 的映射,因为该映射实际上并没有被创建。 If you want to continue using the Automapper you can create a convention如果您想继续使用 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...
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM