首页 文章

指定Fluent NHibernate自动化以向所有实体添加唯一约束

提问于
浏览
2

我的自动化:

return Fluently.Configure()
                .Database(config)
                .Mappings(m =>
                          m.AutoMappings.Add(
                              AutoMap.AssemblyOf<Company>()
                                  .Where(
                                  t => t.Namespace == "DAL.DomainModel" && t.IsClass)
                                  .IgnoreBase<ReferenceEntity>()))
                .BuildSessionFactory();

所以ReferenceEntity是一个包含字符串Name的抽象类,我的所有引用实体都继承自这个类 . 我想修改我的自动化,为从ReferenceEntity继承的所有实体的Name字段添加一个唯一约束 .

我已经收集了它与设置有关 . 但是我对如何继续有点迷失 .

note: 我正在使用Fluent NHibernate v1.0 RTM,因此如果这与我的目标相关,那么约定将采用新风格 .

1 回答

  • 2

    如果您的所有实体都继承自ReferenceEntity,您是否不希望在映射的所有实体上为 Name 属性创建唯一约束?

    但是,如果要按实体基类进行过滤,则可以执行此操作 . 使用约定将唯一约束添加到映射:

    public class NameConvention : IPropertyConvention
    {
        public void Apply(IPropertyInstance instance)
        {
            // Check the entity base class type
            if (instance.EntityType.BaseType.Name == "ReferenceEntity")
            {
                // Only add constraint to the .Name property
                if (instance.Name == "Name")
                {
                    instance.Unique();
                }
            }
        }
    }
    

    要获得FNH选择的约定(以及程序集中的所有其他约定),只需将此行添加到上面的 AutoMap 设置:

    .Conventions.AddFromAssemblyOf<NameConvention>()
    

    亚历克斯,

    没有答案不会改变 . 这是一个例子,使用上面的约定 .

    public abstract class ReferenceEntity
    {
        public virtual int Id { get; protected set; }
        public virtual string Name { get; set; }
    }
    
    public class User : ReferenceEntity
    {
        public virtual string Email { get; set; }
    }
    
    public class Item : ReferenceEntity
    {
        public virtual string Description { get; set; }
    }
    

    这会创建sql:

    create table Users (
        Id INTEGER not null,
       Email TEXT not null,
       Name TEXT not null unique,
       primary key (Id)
    )
    
    create table Items (
        Id INTEGER not null,
       Description TEXT,
       Name TEXT not null unique,
       primary key (Id)
    )
    

    只要这些是单独的实体,它将为每个实体的.Name属性创建唯一约束 .

相关问题