Store Lambda expressions as variable

c# entity-framework entity-framework-core lambda

Question

Is it possible to store a lambda expression as a variable and use it in multiple places. My db objects have an Id as int and a UId as an uniqueidentifier and I have to write very similar expressions when selecting based on Id or 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));

Is it possible to:

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

then use the variable like:

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

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

I know the syntax is wrong, it's just what I'm looking for.

1
2
11/19/2017 12:58:42 AM

Accepted Answer

You can just create a method that returns an IQueryable<Category>. If you want the usage to be the same as your example then this could be an 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;
}

You can then use this as follows:

await this.Worker
    .GetRepo<Category>()
    .GetExpression()
    .SingleAsync(cat => cat.UId.Equals(uid));
3
11/11/2018 11:08:15 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow