0

我有产品 (p) 和材料 (m) 的多对多关系以及 products2materials 表 (p2m) 作为多对多链接。

我需要得到

- all products that have materials assigned,
- all products with no materials assigned,
- and all materials with no products assigned.

基本上是存在的东西的结合。但是,由于这将是一个数据过滤器,我需要过滤掉与搜索条件不匹配的产品和/或材料(例如,所有以“A”开头的产品等)。

如何在 LINQ-to-EF 4.1 中执行此操作?

非常感谢!

4

3 回答 3

1

以下应该做的工作:

from m in context.Materials //m has to be the first
from p in context.Products    
where !p.Select(p1 => p1.Material).Contains(m) || p.Material == null || p.Material == m

对于性能,以下可能会更好:

var a = from p in context.Products select p.Material;

var b = from m in context.Materials //m has to be the first
        from p in context.Products    
        where a.Contains(m) || p.Material == null || p.Material == m 
于 2013-11-11T21:41:20.923 回答
0

从您的描述看来,您实际上需要:

  1. 所有产品
  2. 所有未使用的材料

您需要将它作为单个 IQueryable(如果是,您需要哪些字段)还是作为 2 个 IQueryable?

于 2012-01-24T15:48:59.510 回答
0

Linq 不直接提供完全外连接操作,因此您最好的选择是尝试单独的左连接和右连接 L2E 查询并将它们联合到单个结果集。

我会尝试类似(未测试):

var query = (from p in context.Products
             from m in p.Materials
             select new { p, m })
            .Union(
             from m in context.Materials
             from p in m.Products
             select new { p, m })
            ...

也许您将不得不使用DefaultIfEmpty来强制执行外部连接。

于 2012-01-24T13:50:51.587 回答