使用Entity Framework从SQL数据库中获取所有内容

时间:2013-02-04 07:41:17

标签: c# sql-server linq entity-framework linq-to-entities

我有一个像这样的产品列表

var r = db.Products.Where(x => x.Sites
                                .Where(z => z.Key == associatedProducts.Key)
                                .Any()
                  ).ToList()

有一个名为Products的实体,我想从产品中获取所有元素,但RelatedProducts.Products中存在这些元素

我该怎么做?

3 个答案:

答案 0 :(得分:15)

如果在previos查询中使用EF获取了associatedProducts列表,则以下查询有效。

var temp = db.Products.ToList().Except(associatedProducts).ToList();

否则,如果associatedProducts是未使用EF获取的列表(假设Key是整数);

List<int> tempIdList = associatedProducts.Select(q => q.Key ).ToList();
var temp = db.Products.Where(q => !tempIdList.Contains(q.Key));

答案 1 :(得分:0)

            var query = from p in db.Products
                        where !(from a in associatedProducts.Products
                                select a.Products)
                                .Contains(p.Key)
                        select p;

我没有测试查询,但看起来应该是这样。

你应该看看如何在linq中使用“not in”:
How would you do a "not in" query with LINQ?

答案 2 :(得分:-3)

您可以加载要排除的产品列表,然后从所有产品列表中加载.Exclude()