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