2009-09-14 44 views
1

我想使用Example.Create()來查詢一個實例的唯一值。要做到這一點,我需要找出已經設置映射文件中的唯一鍵屬性的值,就像這樣:如何使用NHibernate查詢唯一鍵值

<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」?

回答

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。它當然可以變得更高效!它也不會對錯誤條件進行任何捕獲(例如,如果給它一個不正確的鍵名或未映射的類類型,它將會崩潰)。

乾杯, 約翰

+0

謝謝!使用NHibernate.Cfg.Configuration是我需要的提示。我原本以爲我可以使用SessionFactory.GetClassMetadata()函數來解決這個問題。 – Martin 2009-09-15 09:43:09