Linq with Lambda SQL equivalent

I am relatively new to entity structure and I was trying to write a Linq statement with Lambda that includes a simple join. I have three tables: Staff - StaffRole - Role.

Partial diagram

I want an employee in a certain role to satisfy a certain condition. Its very simple to write in plain SQL:

SELECT *
FROM Staff s
INNER JOIN StaffRole sr ON s.StaffId = sr.StaffId
INNER JOIN Role r ON sr.RoleId = r.RoleId
WHERE r.Description = 'SpecialisedHealthManager'
AND s.PrimaryShm = 0

Now, writing it in a Linq expression, I had no luck. I think it will be something like this:

var actingShm = db.Staff.Join(db.StaffRole,
                           inner => inner.StaffId,
                           outer => outer.Role,
                           (outer, inner) => new
                           {
                               StaffId = inner.StaffId,
                               FirstName = inner.Staff.FirstName,
                               Surname = inner.Staff.Surname,
                               SamAccountName = inner.Staff.SamAccountName,
                               RoleId = outer.Description
                           });

Needless to say, this does not work.

+4
source share
3 answers

Try using it as follows:

var list = from s in Staff
join sr in StaffRole on s.StaffId equals sr.StaffId
join r in Role on sr.RoleId equals r.RoleId
where r.Description == 'SpecialisedHealthManager' && s.PrimaryShm == 0
select new
{
   StaffId = s.StaffId,
   FirstName = s.Staff.FirstName,
   Surname = s.Staff.Surname, 
   SamAccountName = s.Staff.SamAccountName,
   RoleId = r.Description
});
+3
source

See if you really want to do this using the LINQ method syntax:

SO lambdas

:

http://msdn.microsoft.com/pl-pl/library/bb534675(v=vs.110).aspx

. , , .

+2

You must have your associations configured so that you can do this ...

var actingShm = from s in db.Staff
                from r in s.Roles
                where r.Description == "SpecialisedHealthManager"
                select new
                       {
                           StaffId = s.StaffId,
                           FirstName = s.FirstName,
                           Surname = s.Surname,
                           SamAccountName = s.SamAccountName,
                           RoleId = r.Description
                       });

Are you using Entity Framework or Linq2SQL?

+1
source

Source: https://habr.com/ru/post/1537633/


All Articles