在Linq to Entity 中使用lambda表達式來實現Left Join和Join

一、讀取用戶和部門兩個表的左鏈接:express

var sg = db.Users.GroupJoin(db.Departments, u => u.DepartmentId, d => d.DepartmentId, (u,d) => new { u, d }).Select(o=>o).ToList();

注意:上面將返回所用用戶信息和對應的部門信息(即用戶部門ID信息缺乏,那麼用戶列表也會顯示)spa

 

二、讀取指定返回列表字段的左鏈接信息:code

 var GJoinList = db.Sys_User.GroupJoin(db.Sys_Department, u => u.DepartmentId, d => d.DepartmentId, (u,d) => new { UserId=u.UserId, Account=u.Account, RealName=u.RealName, EnabledMark=u.EnabledMark, DeleteMark=u.DeleteMark,DepartmentName = d.FirstOrDefault(x=>x.DepartmentId==u.DepartmentId).FullName}).Select(o=>o);

 

三、讀取鏈接表:blog

var sg = db.Users.Join(db.Departments, u => u.DepartmentId, d => d.DepartmentId, (u,d) => new { u, d }).Select(o=>o).ToList();

注意:這裏將只顯示用戶裏DepartmentId和部門表裏DepartmentId相等的信息,若是用戶沒有部門ID則此條用戶信息不會顯示ip

 

 var data = db.CRM_OrderDetails.Join(db.CRM_Order, d => d.OrderId, o => o.OrderId, (d, o) => new { d, o }).Select(p => new ProductsListModel() {
                OrderId =p.o.OrderId,
                OrderCode=p.o.OrderCode,
                CustomerName=p.o.CustomerName,
                ProductName=p.d.ProductName,
                UnitId=p.d.UnitId,
                Qty=p.d.Qty,
                Price=p.d.Price,
                Amount=p.d.Amount,
                TaxAmount=p.d.TaxAmount,
                TaxCostAmount=p.d.TaxCostAmount,
                CreateTime=p.d.CreateTime,
                EndTime=p.d.EndTime,
                Description=p.d.Description
            }).Where(expression).OrderBy(orderbyExpression);
相關文章
相關標籤/搜索