使用Fluent NHibernate生成表索引

25

使用Fluent NHibernate是否可以生成表索引以及其余的数据库模式?我想通过自动化构建流程来生成完整的数据库DDL。

3个回答

49

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

Map(x => x.Prop1).Index("idx__Prop1");

正确,API已经更改,这现在被认为是设置索引的正确方法。我已经更新了这个问题的答案以反映这个变化。谢谢。 - Todd Brooks

15

您是指对列进行索引吗?

您可以在ClassMap<...>文件中手动完成,通过添加 .SetAttribute("index", "nameOfMyIndex") 来实现,例如:

Map(c => c.FirstName).SetAttribute("index", "idx__firstname");

您可以通过使用Automapper的属性特性来完成此操作,例如:

在创建持久化模型后:

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

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


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

然后对你的实体执行以下操作:

[Indexed]
public virtual string FirstName { get; set; }

我喜欢后者。它在不侵入你的领域模型的同时,仍然非常有效和清晰地说明了发生了什么,这是一个很好的折衷方案。


10

Mookid的答案很棒,对我帮助很大,但与此同时,不断发展的Fluent NHibernate API已经有所变化。

因此,现在编写mookid示例的正确方式如下:

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

其中 IndexedPropertyConvention 是以下内容:

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

现在,[Indexed] 属性的工作方式与以前相同。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接