ef核心2.1中的COUNT(DISTINCT *)

时间:2018-07-19 04:37:18

标签: c# linq asp.net-core-2.1 ef-core-2.1

   SELECT e.EmpName,me.RemarkNumber,me.RemarkPeopleNumber 
     FROM EmployeeInfo e 
LEFT JOIN 
          (SELECT COUNT(RemarkId) 
               As RemarkNumber,COUNT(DISTINCT MemberId) 
               As RemarkPeopleNumber,CreateUser 
             FROM MemberRemark 
             WHERE RemarkStatus=0 
          GROUP BY CreateUser) 
                AS me 
                On e.EmpName=me.CreateUser
             WHERE BranchCode = '0000' 
               And [Status]=0

如何转换为linq

 from e in db.EmployeeInfo
                join me in (
                    from memberRemarks in db.MemberRemark
                    where
                        memberRemarks.RemarkStatus == 0
                    group memberRemarks by new
                    {
                        memberRemarks.CreateUser,
                    }
                    into g
                    select new
                    {
                        RemarkNumber = g.Count(),
                        RemarkPeopleNumber = g.Select(m=>m.MemberId).Distinct().Count(),
                        g.Key.CreateUser
                    }) on new {e.EmpName} equals new {EmpName = me.CreateUser} into meJoin
                from me in meJoin.DefaultIfEmpty()
                where
                    e.BranchCode == "0000" &&
                    e.Status == 0
                select new
                {
                    e.EmpName,
                    me.RemarkNumber,
                    me.RemarkPeopleNumber
                };
  

RemarkPeopleNumber = g.Select(m => m.MemberId).Distinct()。Count(),   //错误

这行代码出错

asp.net核心mvc 2.1 + ef核心2.1 + mssql

如何修改此代码

1 个答案:

答案 0 :(得分:1)

也许您将查询分为几部分会更好?使用我的SQL to LINQ Recipe,我将像这样翻译您的SQL:

var ePart = from e in db.EmployeeInfo
            where e.BranchCode == "0000" && e.Status == 0
            select e;
var mrPart = from mr in db.MemberRemark
             where mr.RemarkStatus == 0
             group mr by mr.CreateUser into mrg
             select new {
                 CreateUser = mrg.Key,
                 RemarkNumber = mrg.Count(),
                 RemarkPeopleNumber = mrg.Select(mr => mr.MemberId).Distinct().Count()
             };
var ans = from e in ePart
          join me in mrPart on e.EmpName equals me.CreateUser into mej
          from me in mej
          select new {
            e.EmpName,
            me.RemarkNumber,
            me.RemarkPeopleNumber
          };