如何在linq中使用我们在sql中使用的左连接?

k2fxgqgv  于 2023-03-10  发布在  其他
关注(0)|答案(5)|浏览(156)

我如何在我写SQL查询的Linq中使用左连接?

select 
    p.Name, p.Family,
    E.EmployTypecode, E.employtypeName, E.EmplytyppeTye 
from 
    personnel as p
left join 
    Employee as E on E.EmployTypecode = p.EmployTypecode
p8h8hvxi

p8h8hvxi1#

使用Join关键字代替Left连接,并且必须使用“INTO”关键字和“DefaultIfEmpty()”方法,因为右表返回空值。

var query = from p in personnel 
               join e in Employee on p.EmployTypecode equals e.EmployTypecode into t
               from nt in t.DefaultIfEmpty()
               orderby p.Name

    select new
    {
        p.Name, p.Family,
        EmployTypecode=(int?)nt.EmployTypecode,  // To handle null value if Employtypecode is specified as not null in Employee table.
        nt.employtypeName, nt.EmplytyppeTye
    }.ToList();
nhn9ugyo

nhn9ugyo2#

这样做:

var query = 
from  p in personnel
join e in Employee 
    on p.EmployTypecode equals e.EmployTypecode
into temp
from j in temp.DefaultIfEmpty()
select new
{
    name = p.name,
    family = p.family,
    EmployTypecode = String.IsNullOrEmpty(j.EmployTypecode) ? "" : j.EmployTypecode,
    ......
}
368yc8dk

368yc8dk3#

var q=(
              from pd in dataContext.personnel 
              join od in dataContext.Employee 
                  on pd.EmployTypecode equals od.EmployTypecode 
                  into t 
              from rt in t.DefaultIfEmpty() 
              orderby pd.EmployTypecode 
              select new 
              {  
                  EmployTypecode=(int?)rt.EmployTypecode,
                  pd.Name, 
                  pd.Family,  
                  rt.EmplytyppeTye 
              }
         ).ToList();
vbopmzt1

vbopmzt14#

你可以像下面这样在Linq中编写lambda和query
使用查询语法

var resultOfQuery = (from u in users
            join p in managers on u.Manager equals p.Email into ps
            from p in ps.DefaultIfEmpty()
            select new
            {
                User = u,
                Manager = p
            }).ToList();

使用Lambda

var resultOfQUery = users.GroupJoin(managers, u => u.Manager, p => p.Email, (u, ps) => new {u, ps})
            .SelectMany(t => t.ps.DefaultIfEmpty(),
                (t, p) => new
                {
                    User = t.u,
                    Manager = p
                });
inb24sb2

inb24sb25#

为什么不使用SQL查询将EF转换为LIST。在EF 6.1中

public class personnel
    {
        public String Name { get; set; }
        public String Family { get; set; }
        public String EmployTypecode { get; set; }
        public String employtypeName { get; set; }
        public String EmplytyppeTye { get; set; }
    }

List<personnel> personnels = dbentities.Database.SqlQuery<personnel>(@"select 
    p.Name, p.Family,
    E.EmployTypecode, E.employtypeName, E.EmplytyppeTye 
from 
    personnel as p
left join 
    Employee as E on E.EmployTypecode = p.EmployTypecode ").ToList();

相关问题