문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top