在LINQ中需要一个子查询

时间:2014-05-05 14:21:56

标签: c# .net linq asp.net-mvc-4 linq-to-sql

我想选择此表中的所有项目:

_categoryRepository.Table :

Id  Name

1   Birthday
2   Christmas
4   Desktops
6   Notebooks
7   Accessories
9   Cell phones

但是,。 。我想从_categoryRepository中排除与此表中的'EventID'匹配的任何'Id':

_MemberEventRepository.Table

Id  MemID   EventID

1   1   1
3   1   2
5   1   7
7   4   1
8   4   4

匹配MemId。因此,对于MemID'1',结果将是:

4   Desktops
6   Notebooks
9   Cell phones

我不知道如何在LINQ中执行此操作。

    var eventsList = from c in _categoryRepository.Table
                    join m in _MemberEventRepository.Table on ?????????????
                    where (m.MemID == currentCustomer)         
                    orderby c.Name
                    select new MyActiveEvents { Id = c.Id, Name = c.Name };

这相当于SQL:

SELECT [Id] ,[Name]
FROM [Category] 
WHERE Id NOT IN 
(SELECT EventID FROM [Category] c INNER JOIN [MemberEvent] m ON m.[EventID] = c.Id)

这在LINQ中是否可行?

2 个答案:

答案 0 :(得分:2)

应该是这样的:

var categories = db.Categories
                   .Where(c => db.MemberEvents.Count(e => EventID == c.Id) == 0);

更新 - 使用您的LINQ代码片段:

var eventsList = from c in _categoryRepository.Table
                 where _MemberEventRepository.Table
                     .Count(m => m.EventID == c.id) == 0       
                 orderby c.Name
                 select new MyActiveEvents { Id = c.Id, Name = c.Name }

也可以使用Count(...) == 0来代替!Any(...)

答案 1 :(得分:1)

也许除了会工作?我不确定哪种解决方案会转化为最有效的sql。

var eventsList = (from c in _categoryRepository.Table
                  orderby c.Name
                  select new MyActiveEvents { Id = c.Id, Name = c.Name })
                 .Except(
                from c in _categoryRepository.Table
                join m in _MemberEventRepository.Table on c.Id equals m.EventID
                where (m.MemID == currentCustomer)         
                select new MyActiveEvents { Id = c.Id, Name = c.Name });