c# – Linq to Sql Count包含连接
我有一个
Linq to sql如下:
var members=db.Members.Include(x=> x.Contact).Count(); 现在由于一些不良数据,我的成员中的所有联系人都没有相应的联系人记录.因此,在计数期间,如何将内部联接后的计数包含在Contact表中. 问题是,当我获得成员列表时,成员列表有100个记录,而Count有150个记录(50个记录是坏数据). var membersQ=db.Members.Include(x=> x.Contact).Select(i=> new MemberViewModel(){ Name = i.Contact.Name,ContactId= i.Contact.Id,CreatedDate= i.CreatedDate }).AsQueryable(); var members=memberQ.ToList();// =100,paging is done... // the memebers list uses paging but the count doesn't var total=membersQ.Count(); // =150 我在计数期间检查了结果查询,显然它没有与Contact表进行JOIN而Count() 更新 Member Table Id ContactId,CompanyId,CreatedDate ... Contact Table Id Name ... Member表中ContactId的外键不是在数据库级别设置,而是仅在Model上设置. [ForeignKey("ContactId")] Public Contact Contact { get; set; } 糟糕的数据是这样的 我之前有1,2,3,4,5,6,7,8,9,10作为联系人记录,所有这些联系人也在会员表中. 现在我从Contact表中删除记录,比如说6-10.但碰巧没有从会员表中删除. 所以这导致计数问题.是的,从成员中删除不良数据可以解决问题,但问题是如何在使用Count()时使用join. 注意:我使用数据库初始化器null 更新2 对于查询: (from a in Members join b in Contacts on a.ContactId equals b.ContactId select a).Count() 使用默认Linq To SQL SELECT COUNT(*) AS [value] FROM [Member] AS [t0] INNER JOIN [Contact] AS [t1] ON [t0].[ContactID] = [t1].[ContactID] 使用Entityframework DbContext SELECT [GroupBy1].[A1] AS [C1] FROM ( SELECT COUNT(1) AS [A1] FROM [dbo].[Member] AS [Extent1] ) AS [GroupBy1] 在我的代码中,我使用DbContext方法.所以……不知道该怎么做 解决方法
那这个呢:
var x = from m in Members join c in Contacts on m.ContactId equals c.ID select new { Name = c.Name,ContactId= c.ID,CreatedDate= c.CreatedDate }; Console.Write(x.Count()); 编辑 当我使用LinqPad与此查询并查看生成的SQL时,我得到: SELECT COUNT(*) AS [value] FROM [Members] AS [t0] INNER JOIN [Contact] AS [t1] ON [t0].[ContactId] = ([t1].[ID]) 编辑2 你也可以试试这个: var x = from c in Contacts from m in Members where m.ContactId == c.ID select new { Name = c.Name,CreatedDate= c.CreatedDate }; Console.Write(x.Count()); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |