使用Fluent NHibernate生成表索引

Tod*_*oks 25 nhibernate nhibernate-mapping fluent-nhibernate

是否可以使用Fluent NHibernate生成表索引以及数据库模式的其余部分?我希望能够通过自动构建过程生成完整的数据库DDL.

Pau*_*tum 48

在更新版本的Fluent NHibernate中,您可以调用Index()方法来执行此操作而不是使用SetAttribute(不再存在):

Map(x => x.Prop1).Index("idx__Prop1");
Run Code Online (Sandbox Code Playgroud)


moo*_*000 15

你的意思是列上的索引吗?

您可以ClassMap<...>通过附加手动在文件中手动执行此操作.SetAttribute("index", "nameOfMyIndex"),例如:

Map(c => c.FirstName).SetAttribute("index", "idx__firstname");
Run Code Online (Sandbox Code Playgroud)

或者你可以使用automapper的属性功能来实现 - 例如:

创建持久性模型后:

{
    var model = new AutoPersistenceModel
    {
        (...)
    }

    model.Conventions.ForAttribute<IndexedAttribute>(ApplyIndex);
}


void ApplyIndex(IndexedAttribute attr, IProperty info)
{
    info.SetAttribute("index", "idx__" + info.Property.Name");
}
Run Code Online (Sandbox Code Playgroud)

然后对你的实体这样做:

[Indexed]
public virtual string FirstName { get; set; }
Run Code Online (Sandbox Code Playgroud)

我喜欢后者.在对您的域模型不是非侵入性的情况下,仍然是非常有效且清楚正在发生的事情之间是一个很好的折衷方案.


Yan*_*rtz 10

Mookid的答案非常棒,对我帮助很大,但同时不断发展的Fluent NHibernate API也发生了变化.

那么,现在编写mookid样本的正确方法如下:

//...
model.ConventionDiscovery.Setup(s =>
            {
                s.Add<IndexedPropertyConvention>();
                //other conventions to add...
            });
Run Code Online (Sandbox Code Playgroud)

其中IndexedPropertyConvention如下:

public class IndexedPropertyConvention : AttributePropertyConvention<IndexedAttribute>  
{
    protected override void Apply(IndexedAttribute attribute, IProperty target)
    {
         target.SetAttribute("index", "idx__" + target.Property.Name);
    }
}
Run Code Online (Sandbox Code Playgroud)

[Indexed]属性现在的工作方式相同.