【发布时间】: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>
【问题讨论】:
-
你可能想看看
Func<T, TResult>(msdn.microsoft.com/en-us/library/bb549151(v=vs.110).aspx),它应该可以让你做你想做的事。 -
@Chris,或者有时是
Expression<>,即Expression<Func<T, TResult>>,因为某些Linq 风格需要一个表达式树,才能翻译成例如SQL,并且不能使用普通的 .NET 委托实例。
标签: c# entity-framework lambda entity-framework-core