我有3种几乎完全相同的方法:
protected DetachedCriteria GetAvailableFundIdsPerDataUniverse()
{
return GetAvailableIdsPerDataUniverse()
.SetProjection(LambdaProjection.Property<Fund>(f => f.Id));
}
protected DetachedCriteria GetAvailableCompanyIdsPerDataUniverse()
{
return GetAvailableIdsPerDataUniverse()
.SetProjection(LambdaProjection.Property<Fund>(f => f.Company.Id));
}
protected DetachedCriteria GetAvailableCategoryIdsPerDataUniverse()
{
return GetAvailableIdsPerDataUniverse()
.SetProjection(LambdaProjection.Property<Fund>(f => f.Category.Id));
}
其中GetAvailableIdsPerDataUniverse()
定义为:
protected DetachedCriteria GetAvailableIdsPerDataUniverse()
{
return DetachedCriteria.For<Fund>()
.SetFetchMode<Fund>(f => f.ShareClasses, FetchMode.Join)
.CreateCriteria<Fund>(f => f.ShareClasses)
.Add(LambdaSubquery.Property<ShareClass>(x => x.Id).In(GetAvailableShareClassIdsPerDataUniverse()))
.Add<ShareClass>(f => f.ExcludeFromFT == false);
}
对于每种方法,唯一的区别是用于选择数据的表达式,即
f => f.Id
,f => f.Company.Id
和f => f.Category.Id
有人可以告诉我是否可以将这些差异作为变量传递给GetAvailableIdsPerDataUniverse()
,这样我只能有1个方法而不是4个?
答案 0 :(得分:4)
直接在浏览器中输入,因此可能不包含错误
protected DetachedCriteria GetAvailableIdsPerDataUniverse(Expression<Fund, int> e)
{
return DetachedCriteria.For<Fund>()
.SetFetchMode<Fund>(f => f.ShareClasses, FetchMode.Join)
.CreateCriteria<Fund>(f => f.ShareClasses)
.Add(LambdaSubquery.Property<ShareClass>(x => x.Id).In(GetAvailableShareClassIdsPerDataUniverse()))
.Add<ShareClass>(f => f.ExcludeFromFT == false).
.SetProjection(LambdaProjection.Property<Fund>(e));
}
GetAvailableIdsPerDataUniverse(e => e.Category.Id)
//...
修改强> 我查了NHibernate.LambdaExtensions的文档,LambdaProjection.Property的类型是
public static PropertyProjection Property<T>(Expression<Func<T, object>> expression)
所以参数类型应为
System.Linq.Expressions.Expression<Func<Fund, object>>