接受lambda作为字段名称列表的C#创建方法 [英] c# create method that accept lambda for list of field name

查看:215
本文介绍了接受lambda作为字段名称列表的C#创建方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一种可以与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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆