2010-09-08 72 views
1

如果您指定要從示例中排除哪些屬性,Example類非常棒。但是如果你想指定要包含哪些屬性呢?NHibernate ExcludeProperty:爲什麼沒有IncludeProperty

以此示例爲例:在數據庫中尋找具有相同名稱的人員。 Person對象具有許多屬性。所以要使用NHibernate.Criterion.Example對象,我必須指定要排除的每個字段 - 可能有很多。

爲什麼沒有IncludeProperty方法?

我有一個Person對象,我想根據預先設置的業務規則(FirstName,LastName,DateOfBirth)來查看它是否是重複的。這些規則可以改變,包括一個郵政編碼或其他東西 - 我想做出可配置的。

有沒有簡單的方法呢?

+0

爲什麼不能排除SELECT中的列? – 2010-09-08 15:26:38

+0

我不想在我的代碼中有任何SQL。通過包含SQL,我可以將自己與特定的數據庫技術捆綁在一起。 我只想使用這些對象。 – CarllDev 2010-09-08 16:22:00

回答

1

我有一個解決問題IncludeProperty:

private Type persitentType = typeof(T); 
public IList<T> GetByExample(T exampleInstance, params string[] propertiesToInclude) 
{ 
    // get the properties that will be excluded 
    List<string> propertiesToExclude = 
     persitentType.GetProperties().Where(p => propertiesToInclude.Contains(p.Name) == false).Select(p => p.Name).ToList(); 

    // create the criteria based on the example and excluding the given properties 
    ICriteria criteria = NHibernateSession.CreateCriteria(persitentType); 
    Example example = Example.Create(exampleInstance); 
    foreach (string propertyToExclude in propertiesToExclude) 
    { 
     example.ExcludeProperty(propertyToExclude); 
    } 
    criteria.Add(example); 

    // return the result 
    return criteria.List<T>(); 
} 

添加這個方法到存儲庫類。它使用反射來確定指定對象具有的屬性,然後根據已指定爲包含的屬性找到要排除的屬性。