[英]Cannot convert lambda expression to type 'object'
How can I get this Lambda expression to work in Entity Framework?如何让这个 Lambda 表达式在 Entity Framework 中工作?
Basically, if there is a goalCyleId
, then look it up and get the end date of it.基本上,如果有goalCyleId
,则查找它并获取它的结束日期。
.Select(x => new GoalDTO()
{
GoalId = x.GoalId,
Name = x.Name,
DueDate = x.GoalCycleId == null ? null : _context.GoalCycles.Find(y => y.GoalCycleId == x.GoalCycleId).EndDate
})
I'm getting an error我收到一个错误
Cannot convert lambda expression to type 'object' because it is not a delegate type无法将 lambda 表达式转换为类型“object”,因为它不是委托类型
Try to use the below query,尝试使用以下查询,
.Select(x => new GoalDTO() {
GoalId = x.GoalId,
Name = x.Name,
DueDate = x.GoalCycleId == null ? null : _context.GoalCycles.FirstOrDefault(y => y.GoalCycleId == x.GoalCycleId).EndDate
})
If your entities are set up with the navigation properties, you should just need something like:如果你的实体设置了导航属性,你应该只需要像这样的东西:
.Select(x => new GoalDTO()
{
GoalId = x.GoalId,
Name = x.Name,
DueDate = x.GoalCycle.EndDate
})
GoalCycleId on the Goal may be Null-able, so a GoalCycle navigation reference may be #null but when EF projects this down it would leave DueDate #null if there is no GoalCycle for that Goal, otherwise taking the End Date.目标上的 GoalCycleId 可能可以为空,因此 GoalCycle 导航引用可能为 #null,但是当 EF 向下投影时,如果该目标没有 GoalCycle,它将保留 DueDate #null,否则采用结束日期。 However, that would trip a NullReferenceException
if the Select
is being done after the EF query is materialized.但是,如果Select
在实体化 EF 查询之后执行,那将引发NullReferenceException
。 (Ie premature ToList()
) (即过早ToList()
)
It shouldn't complain with:它不应该抱怨:
DueDate = x.GoalCycle?.EndDate
Find
method of the DbSet class expects a primary key value as its parameter, but you are passing it a lambda expression. DbSet class 的Find
方法需要一个主键值作为其参数,但您向它传递了一个 lambda 表达式。 Use FirstOrDefault
instead.请改用FirstOrDefault
。 _context.GoalCycles.FirstOrDefault(y => y.GoalCycleId == x.GoalCycleId).EndDate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.