Using the “let” kewword in a LINQ Query with EF 4.3

江枫思渺然 提交于 2019-12-22 05:59:15

问题


I have simple LINQ problem that I can't figure out. I have a table Users and a table Employees. One User can have 0...n employees.

I'd like to do something like this:

var result = from u in context.users
             where u.UsrId = 2
             let e = u.Employees.First()
             select new 
{
  UserId = u.UsrId,
  FirstName = e.FirstName
};

That does not work of course becasue the First() call is illegal. First() can only come at the end of a select. What also did not work is to select the employee in a previous query like so:

var employee = from e. in context.Employees.....

...and then say let e = employee instead of let e = u.Employees().First()

I am not sure if the use of let correct. I thought it is for subqueries.

The reason for the First() call is that the Employees table should not have more than one entry for each user. That is a mistake in the design and I have to deal with it now. So I just want the first one.


回答1:


var result = from u in context.users
let e = u.Employees.FirstOrDefault(x => x.bossId == u.UsrId)
where u.UsrId = 2
select new  {   UserId = u.UsrId,   FirstName = e.FirstName }; 

Just a tipp without test.




回答2:


First can be used except in the middle of a LINQ queriable statement, when translating that statement to SQL theres actually no way to constitute a First as its behavior is to throw an error. FirstOrDefault however can be translated to Top(1) which is how its transformed to SQL. This means using first in the middle of a SQL translatable statement isnt really valid, however i believe they have allowed this as the last statement as a zero result can be translated to an exception post query execution.



来源:https://stackoverflow.com/questions/9480023/using-the-let-kewword-in-a-linq-query-with-ef-4-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!