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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With