Gaurav123
Gaurav123

Reputation: 5209

How to convert sql query into Linq to entities?

I am new to joins in linq to entities. I have one query in sql server and want to convert it into LINQ to Entities.

Can someone please provide the solution for the same? Do we have any online tool to convert sql queries to LINQ to entities?

 SELECT  R.ID,r.Name,u.UserId
      FROM Roles R
      Left JOIN UserRoles U ON r.Id = u.RoleId 
      AND   [UserId] = '5'
      where  [UserId] IS NULL 

Upvotes: 0

Views: 1161

Answers (2)

user449689
user449689

Reputation: 3154

DefaultIfEmpty will result in a left outer join, therefore as you want a simple left join you should do as follows:

var list = (from r in context.Roles
    join u in context.UsersRoles on r.Id equals u.RoleId && u.UserId='5' into x
    where r.UserId == null
    select new
    {
        r.Id,
        r.Name,
        u.UserId
    }).ToList();

Upvotes: 1

var list = (from r in context.Roles
    join ur in context.UsersRoles on r.Id equals ur.RoleId && ur.UserId='5' into x
    from y in x.DefaultIfEmpty()        
    where r.UserId ==null
    select new Object
    {
        Id = r.Id,
        Name = r.Name,
        ur.UserId
    }).ToList();

Note: Not understand your second UserId IS NULL logic

Upvotes: 0

Related Questions