gt.guybrush gt.guybrush - 4 days ago 6
C# Question

c# create method that accept lambda for list of field name

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?

mww mww
Answer

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
    {
             ////
    }
Comments