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.
Func<T, TResult>(msdn.microsoft.com/en-us/library/bb549151(v=vs.110).aspx) which should allow you to do what you want.Expression<>, that isExpression<Func<T, TResult>>, since some flavors of Linq need an expression tree, to be translated into e.g. SQL, and cannot use a plain .NET delegate instance.