简体   繁体   中英

Count in select query of Linq to SQL

I am trying to convert below SQL query into Linq.

select eg.userid, eg.groupid, count(r.RID) as RecipientCount
from eg
join g on eg.groupid = g.groupid
join r on g.RID = r.RID
where eg.UserId = '7F813844-3B93-418E-8141-654082C4E37D'
  and eg.IsDeleted = 0
  and r.Isdeleted = 0
group by eg.groupid

Above query runs properly in SQL.

My Linq code is:

var v = from eml in dc.egs
        join recpingroup in dc.g on eml.GroupID equals recpingroup.GroupID
        where eml.aspnet_User.LoweredUserName.Equals(strUserName.ToLower()) 
          && !eml.IsDeleted 
          && !recpingroup.r.IsDeleted
        select new Info()
        {
            CreateDt = eml.CreateDt.ToShortDateString(),
            UserId = eml.UserId.ToString(),
            LastUpdateDt = eml.LastUpdateDt.ToShortDateString(),
            Username = eml.aspnet_User.UserName,
            GroupDescription = eml.GroupDescription,
            GroupID = eml.GroupID.ToString().ToUpper(),
            GroupName = eml.GroupName,
            Count = dc.g.Count(r1 => r1.GroupID.Equals(eml.GroupID) && !r1.r.IsDeleted)
        };

where dc is my DataContext.

But I am having problems in the last property ie Count is coming wrong. I want the counts of recipients from recpingroup.r as RecipientCount.

Also note that tables are linked in SQL internally by PK and FK references.

尝试跟随

Count = (from x in dc.g where(r1 => r1.GroupID.Equals(eml.GroupID) && !r1.r.IsDeleted) select x.g).count()

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