EF left join

1

var aList = menu.GetPagedList(page, limit, out totalCount, filter, orderBy).ToList(); //集合1
var bList = menu.GetAll().ToList(); //collection 2
var data = from a in aList
           join b in bList on a.menuParentId equals b.id into temp
           from bb in temp.DefaultIfEmpty()
           select new
           {
               id=a.id,
               menuName = a.menuName,
               menuIcon = a.menuIcon,
               menuParentId = a.menuParentId,
               menuUrl = a.menuUrl,
               menuDescription = a.menuDescription,
               sort = a.sort,
               state = a.state,
               createTime = a.createTime,
               updateTime=a.updateTime,
               parentName = bb == null ?"":bb.menuName //Pay special attention to whether this bb is null
           };
var list = data.ToList ();

Note: The above example uses the DefaultIfEmpty operator, which provides a default element for a real sequence. DefaultIfEmpty uses the default keyword in generics. The default keyword returns null for reference types and 0 for value types. For structure types, they will be initialized to null (reference type) or 0 (value type) according to their member types.


We can not use default, but give the default object value when empty in DefaultIfEmpty. The statement is as follows:

//left join, use default object when empty
var leftJoinQuery =  s in db.Student
join c in db.Course
on s.CourseCno equals c.Cno into gc
from gci in gc.DefaultIfEmpty(
new Course { Cname = "",Cperiod="" } //The default value when set to empty
)
select new
{
    ClassID = s.CourseCno,
    ClassName = gci.Cname,
};


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324884274&siteId=291194637