如果要指定要从示例中排除的属性,则可以使用Example类。但是如果要指定要包含哪些属性呢?
以此为例:在数据库中查找具有相同名称的人员。 Person对象具有许多属性。因此,要使用NHibernate.Criterion.Example对象,我必须指定要排除的每个字段 - 可能很多。
为什么没有IncludeProperty方法?
我有一个Person对象,我想看看它是否是基于预设业务规则(FirstName,LastName,DateOfBirth)的重复项。这些规则可以更改为包含邮政编码或其他内容 - 我想使其可配置。
有一个简单的方法吗?
答案 0 :(得分: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>();
}
将此方法添加到您的存储库类。它使用反射来确定指定对象具有哪些属性,然后根据已指定为包含的属性查找要排除的属性。