【问题标题】:Returning (blanks) in many to many Linq query在多对多 Linq 查询中返回(空白)
【发布时间】:2014-03-16 18:10:58
【问题描述】:

对这个问题的跟进:Changing a linq query to filter on many-many

我有以下 Linq 查询

public static List<string> selectedLocations = new List<string>();

// I then populate selectedLocations with a number of difference strings, each
// corresponding to a valid Location

viewModel.people = (from c in db.People
                select c)
                .OrderBy(x => x.Name)
                .ToList();

// Here I'm basically filtering my dataset to include Locations from
// my array of selectedLocations

viewModel.people = from c in viewModel.people
                where (
                from a in selectedLocations
                where c.Locations.Any(o => o.Name == a)
                select a
                ).Any()
                select c;

如何修改查询,以便它还返回根本没有设置位置的人?

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    您可以在数据库端进行过滤:

    viewModel.people =
        (from p in db.People
         where !p.Locations.Any() || 
                p.Locations.Any(l => selectedLocations.Contains(l.Name))
         orderby p.Name
         select p).ToList();
    

    或 lambda 语法:

    viewModel.people = 
      db.People.Where(p => !p.Locations.Any() ||
                            p.Locations.Any(l => selectedLocations.Contains(l.Name)))
               .OrderBy(p => p.Name)
               .ToList();
    

    在这种情况下,EF 将生成两个 EXISTS 子查询。比如:

    SELECT [Extent1].[Name]
           [Extent1].[Id]
           -- other fields from People table
    FROM [dbo].[People] AS [Extent1]
    WHERE (NOT EXISTS (SELECT 1 AS [C1]
                       FROM [dbo].[PeopleLocations] AS [Extent2]
                       WHERE [Extent2].[PersonId] = [Extent1].[Id])
           OR EXISTS (SELECT 1 AS [C1]
                      FROM [dbo].[PeopleLocations] AS [Extent3]
                      WHERE [Extent3].[PersonId] = [Extent1].[Id])
                            AND [Extent3].[Name] IN ('location1', 'location2')))
    ORDER BY [Extent1].[Name] ASC
    

    【讨论】:

      猜你喜欢
      • 2021-05-01
      • 2010-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多