将Lambda表达式存储为变量

斯坦·统治者

是否可以将lambda表达式存储为变量并在多个地方使用它。我的db对象的Id为int,UId为uniqueidentifier,在基于IdUId选择时,我必须编写非常相似的表达式

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));

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

钙碳

您可以只创建一个返回的方法IQueryable<Category>如果您希望用法与示例相同,则可以使用扩展方法

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));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章