将Lambda表达式存储为变量

时间:2017-11-19 00:58:43

标签: c# entity-framework lambda entity-framework-core

是否可以将lambda表达式存储为变量并在多个位置使用它。 我的db对象的 Id 为int, UId 为uniqueidentifier,我在基于 Id 或<进行选择时必须编写非常相似的表达式EM> UID

LAMBDA

var result = await this.Worker.GetRepo<Category>().DbSet
    .Include(cat => cat.InfoItems)
    .Include(cat => cat.Products)
        .ThenInclude(prd => prd.InfoItems)
    .Include(cat => cat.Products)
        .ThenInclude(prd => prd.GraphicItems)
            .ThenInclude(itm => itm.Graphic)
                .ThenInclude(gfx => gfx.Items)
    .Include(cat => cat.GraphicItems)
        .ThenInclude(gfx => gfx.Graphic)
            .ThenInclude(gfx => gfx.Items)
    .Include(m => m.Modules)
    .SingleAsync(cat => cat.Id.Equals(id));

是否可以:

var expression = .Include(cat => cat.InfoItems)
    .Include(cat => cat.Products)
        .ThenInclude(prd => prd.InfoItems)
    .Include(cat => cat.Products)
        .ThenInclude(prd => prd.GraphicItems)
            .ThenInclude(itm => itm.Graphic)
                .ThenInclude(gfx => gfx.Items)
    .Include(cat => cat.GraphicItems)
        .ThenInclude(gfx => gfx.Graphic)
            .ThenInclude(gfx => gfx.Items)
    .Include(m => m.Modules);

然后使用变量如:

await this.Worker.GetRepo<Category>().expression.SingleAsync(cat => cat.Id.Equals(id));

await this.Worker.GetRepo<Category>().expression.SingleAsync(cat => cat.UId.Equals(uid));
  

我知道语法错误,这正是我正在寻找的。

1 个答案:

答案 0 :(得分:3)

您只需创建一个返回IQueryable<Category>的方法即可。如果您希望用法与您的示例相同,那么这可能是extension method

public static IQueryable<Category> GetExpression(this IQueryable<Category> qry)
{
    var expression = qry.Include(cat => cat.InfoItems)
        .Include(cat => cat.Products)
            .ThenInclude(prd => prd.InfoItems)
        .Include(cat => cat.Products)
            .ThenInclude(prd => prd.GraphicItems)
                .ThenInclude(itm => itm.Graphic)
                    .ThenInclude(gfx => gfx.Items)
        .Include(cat => cat.GraphicItems)
            .ThenInclude(gfx => gfx.Graphic)
                .ThenInclude(gfx => gfx.Items)
        .Include(m => m.Modules);

    return expression;
}

然后您可以按如下方式使用它:

await this.Worker
    .GetRepo<Category>()
    .GetExpression()
    .SingleAsync(cat => cat.UId.Equals(uid));