接受lambda作为字段名称列表的C#创建方法 [英] c# create method that accept lambda for list of field name
问题描述
我想创建一种可以与lambda一起使用的方法:
i want to create a method that can be used with lambda in that way:
return Method<MyClass>(x => x.PropName1, x.PropName2,...);
在它里面,我必须使用tha propName来渴望通过nhibernate加载那些参考字段:
inside it i have to use tha propName to eager load those reference field via nhibernate:
return session.Query<MyClass>()
.Fetch(c => c.PropName1)
.Fetch(c => c.PropName2).ToList();
我查看linq源代码以找到一些类似的内容,然后转到此处:
i look into linq source code to find some similar and went here:
public static void ListEager<TEntity>(IEnumerable<Func<TEntity, TKey>> fields)
但这是不正确的.
怎么办?
推荐答案
您可以执行以下操作,使用通用方法GetList
实现IGeneric
接口和Generic
类,我使用此通用方法并且运行良好
You can do like this, implement IGeneric
interface and Generic
class, with generic method GetList
, i use this generic method and working very well.
public interface IGenericDataRepository<T> where T : class
{
IList<T> GetList(Func<T, bool> where, params Expression<Func<T, object>>[] navigationProperties);
}
public class GenericDataRepository<T> : IGenericDataRepository<T> where T : class
{
public virtual IList<T> GetList(Func<T, bool> where,
params Expression<Func<T, object>>[] navigationProperties)
{
List<T> list;
using (var dbQuery = new session.Query<T>())
{
//Apply eager loading
foreach (Expression<Func<T, object>> navigationProperty in navigationProperties)
dbQuery = dbQuery.Fetch<T, object>(navigationProperty);
list = dbQuery
.AsNoTracking()
.Where(where)
.ToList<T>();
}
return list;
}
}
要使用它,您需要为任何实体创建存储库类,这是我的ProductRepository
类的示例
To use it you need create repository class for any entity, here is example with my ProductRepository
class
public interface IProductRepository:IGenericDataRepository<Product>
{
////
}
public class ProductRepository:GenericDataRepository<Product>,IProductRepository
{
////
}
这篇关于接受lambda作为字段名称列表的C#创建方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!