【问题标题】:Store Lambda expressions as variable将 Lambda 表达式存储为变量
【发布时间】:2017-11-19 00:58:42
【问题描述】:

是否可以将 lambda 表达式存储为变量并在多个地方使用它。 我的 db 对象有一个 Id 作为 int 和一个 UId 作为唯一标识符,当基于 Id 或 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));

我知道语法是错误的,这正是我要找的。​​p>

【问题讨论】:

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


【解决方案1】:

您可以只创建一个返回IQueryable&lt;Category&gt; 的方法。如果您希望用法与您的示例相同,则可以是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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    • 2014-02-20
    相关资源
    最近更新 更多