简体   繁体   中英

How to perform LINQ JOIN with WHERE

I need help to perform JOIN using LINQ with WHERE clause. The problem is when CaseId in events is null(not all events are case related) it results in NOT showing event.

Here is my code:

var queryEvents = (from e in db.events
                 join u in db.users on e.UserID equals u.UserID
                 join c in db.cases on e.CaseID equals c.CaseID
                 where e.UserID == Program.loggedUser.UserID || (e.UserGroupID == Program.loggedUser.UserGroupID && c.AccessLvl>0)
                 select new { User = u.FirstName + " " + u.LastName, e.Name, e.Description, e.StartDate }).OrderByDescending(x => x.StartDate);

            gvAppointments.DataSource = queryEvents.ToList();

I found some examples on how to use LINQ LEFT JOIN using INTO but then I have problem with WHERE statement.I honestly don't know where to put it.

Can someone please help me with this?

var queryEvents = (from e in db.events
             join u in db.users on e.UserID equals u.UserID
             join c in db.cases on e.CaseID equals c.CaseID into cases
             from subC in cases.DefaultIfEmpty()
             where e.UserID == Program.loggedUser.UserID || (e.UserGroupID == Program.loggedUser.UserGroupID && subC?.AccessLvl ?? 0 > 0)
             select new { User = u.FirstName + " " + u.LastName, e.Name, e.Description, e.StartDate }).OrderByDescending(x => x.StartDate);

        gvAppointments.DataSource = queryEvents.ToList();

You only must be aware, that subC might be now null, so you have to go for a default value, accessing it's properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM