Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the "let" kewword in a LINQ Query with EF 4.3

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.

like image 509
John Avatar asked Feb 28 '12 10:02

John


People also ask

What is let keyword in LINQ?

The Let keyword allows you to create a range variable and initialized with the result of the query expression and then you are allowed to use that variable with the upcoming clause in the same query.

Can you use let in C#?

You can do this with the let keyword, which creates a new range variable and initializes it with the result of the expression you supply. Once initialized with a value, the range variable cannot be used to store another value. However, if the range variable holds a queryable type, it can be queried.

What is the difference between EF and LINQ?

Entity Framework is an object-relational mapping (ORM) framework for connecting C# code to external databases, usually SQL Server. LINQ is a query language embedded into C# and a set of extension methods in order to make it useful.

Is LINQ to SQL deprecated?

LINQ to SQL was the first object-relational mapping technology released by Microsoft. It works well in basic scenarios and continues to be supported in Visual Studio, but it's no longer under active development.


1 Answers

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.

like image 61
Peter Kiss Avatar answered Oct 31 '22 11:10

Peter Kiss