i want to create a method that can be used with lambda in that way:
return Method<MyClass>(x => x.PropName1, x.PropName2,...);
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();
i look into linq source code to find some similar and went here:
public static void ListEager<TEntity>(IEnumerable<Func<TEntity, TKey>> fields)
but it's simply not correct.
how can it be done?
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;
}
}
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
{
////
}
i switch to queryover to get more power :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;
}
in this way i can manage reference or hasmany without problem
i left @mww as accepted answer because the main idea is his