C#创建方法接受拉姆达字段名称的列表
我希望创建一个可与拉姆达以这种方式使用的方法:C#创建方法接受拉姆达字段名称的列表
return Method<MyClass>(x => x.PropName1, x.PropName2,...);
里面我必须使用THA PROPNAME跃跃欲试负荷的参考通过NHibernate的领域:
return session.Query<MyClass>()
.Fetch(c => c.PropName1)
.Fetch(c => c.PropName2).ToList();
我看着LINQ源代码,发现一些类似去这里:
public static void ListEager<TEntity>(IEnumerable<Func<TEntity, TKey>> fields)
但它根本不正确。
怎么办?
你可以这样做,实现IGeneric
接口和Generic
类,与泛型方法GetList
,我用这个泛型方法和工作得很好。
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;
}
}
要使用它,你需要的任何实体创建repository类,这里是我的ProductRepository
类的例子
public interface IProductRepository:IGenericDataRepository<Product>
{
////
}
public class ProductRepository:GenericDataRepository<Product>,IProductRepository
{
////
}
的确我在我的ServiceRepository
这不是一个问题,表达式返回“对象”,而不是实际的属性类型? – Evk
@Evk它是GetList不GetSingle它必须返回列表
我切换到queryover以获得更多的权力:d
public IEnumerable<TEntity> List(params Expression<Func<TEntity, object>>[] eagerFields)
{
var query = _session.QueryOver<TEntity>();
query = AddReferenceFetch(query, eagerFields);
return query.TransformUsing(Transformers.DistinctRootEntity).List();
}
private IQueryOver<TEntity, TEntity> AddReferenceFetch(IQueryOver<TEntity, TEntity> query, params Expression<Func<TEntity, object>>[] eagerFields)
{
foreach (Expression<Func<TEntity, object>> field in eagerFields)
query = query.Fetch(field).Eager;
return query;
}
这样我可以管理参考或hasmany没有问题
我离开@mww作为接受的答案,因为主要思想是他的
你想让这个方法接受任意数量的选择器? – Evk
是的,任何数字 –