具有范围变量查询的LINQ实体组

时间:2012-09-19 07:10:00

标签: c# linq entity-framework tsql linq-to-entities

这是我正在尝试转换为LINQ-Entities查询的T-SQL ....

SELECT  [a].[ModLimit], [b].[NumberOfMods]
FROM    [dbo].[Site][a]
INNER JOIN
(
    SELECT          [SiteId], ISNULL(COUNT(*),0) AS [NumberOfMods]
    FROM            [dbo].[Users][a]
    WHERE           [a].[IsMod] = 1
    GROUP BY        [SiteId]
) [b] ON [a].[SiteId] = [b].[SiteId]
WHERE   [a].[SiteId] = 1

到目前为止我正在使用的是什么(不编译......)

from u in db.Set<User>()
join s in db.Set<Site>() on u.SiteId equals s.SiteId
let x = t.ModLimit
where s.SiteId == 1
group u by u.SiteId into g
select new { g,x});

想法?

表格的缩减结构:

网站

SiteId int PK

ModLimit int

用户

UserId int PK

SiteId int FK IsMod

1 个答案:

答案 0 :(得分:1)

这是我迄今为止的最佳尝试(您是否可以提供dbo.site&amp; dbo.users&amp;或者您期望作为输入的一些测试数据的结构?)

            List<User> users = new List<User>();
            users.Add(new User() { SiteId = 0, IsMod = 1, ModLimit = 3 });
            users.Add(new User() { SiteId = 1, IsMod = null, ModLimit = 2 });
            users.Add(new User() { SiteId = 1, IsMod = 1, ModLimit = 2 });
            users.Add(new User() { SiteId = 1, IsMod = 1, ModLimit = 2 });

            var innerSelect = users
                    .Where(o => o.IsMod != null && o.IsMod > 0)
                    .GroupBy(o => o.SiteId)
                    .Select(o => new User
                     {
                         SiteId = o.Key,
                         Counter = o.Count()
                     })
                     .ToList();

            var result = (from u in users
                          join s in innerSelect on u.SiteId equals s.SiteId
                          where u.SiteId == 1
                          select new
                          {
                              u.ModLimit,
                              NumberOfMods = s.Counter
                          })
                          .Distinct()
                          .ToList();
相关问题