如何使用NHibernate按唯一键值进行查询

时间:2009-09-14 09:53:51

标签: c# .net nhibernate unique-key

我想使用Example.Create()来查询实例的唯一值。为此,我需要找出在映射文件中设置的unique-key属性的值,如下所示:

  <property name="MyColumn">
    <column name="MyColumn" unique-key="MyUniqueKeyGroup"/>
  </property>

为了更好地理解 - 这是代码的重要部分:

criteria.Add(Example.Create(myObject).SetPropertySelector(new MyPropertySelector()));

[...]

public class MyPropertySelector: NHibernate.Criterion.Example.IPropertySelector
{
    #region IPropertySelector Member

    public bool Include(object propertyValue, string propertyName, IType type)
    {
         /*  here is where I want to check if the property belongs 
          *  to the unique-key group 'MyUniqueKeyGroup' and return true if so 
          */
    }

    #endregion
}

我需要做些什么来查明属性是否属于唯一键组'MyUniqueKeyGroup'?

1 个答案:

答案 0 :(得分:0)

您需要探测Nhibernate.Cfg.Configuration对象才能获得此功能。你可以在某处构建它以创建你的ISessionFactory实例。这样的事情可能有用:

private NHibernate.Cfg.Configuration _configuration;

[...]

var selector = new MyPropertySelector<MyClass>(_configuration, "MyUniqueKeyGroup");
criteria.Add(Example.Create(myObject)
                    .SetPropertySelector(selector));

[...]

public class MyPropertySelector<T>: NHibernate.Criterion.Example.IPropertySelector
{
    private NHibernate.Cfg.Configuration _onfiguration;
    private IEnumerable<NHibernate.Mapping.Column> _keyColumns;

    public MyPropertySelector(NHibernate.Cfg.Configuration cfg, string keyName)
    {
        _configuration = cfg;
        _keyColumns = _configuration.GetClassMapping(typeof(T))
                                .Table
                                .UniqueKeyIterator
                                .First(key => key.Name == keyName)
                                .ColumnIterator);

    }

    public bool Include(object propertyValue, string propertyName, IType type)
    {
         return _configuration.GetClassMapping(typeof(T))
                          .Properties
                          .First(prop => prop.Name == propertyName)
                          .ColumnIterator
                              .Where(col => !col.IsFormula)
                              .Cast<NHibernate.Mapping.Column>()
                              .Any(col => _keyColumns.Contains(col)))
    }
}

我实际上没有编译它来检查它的工作原理,所以YMMV。它当然可以提高效率!它也不会对错误条件进行任何捕获(例如,如果你给它一个不正确的键名,或者一个未映射的类类型,它就会崩溃)。

干杯, 约翰