[英]LINQ - SELECT DISTINCT with NOT IN
I'm have a SQL statement which I am trying to transform in a LINQ statement... 我有一个SQL语句,正在尝试在LINQ语句中进行转换...
SELECT DISTINCT mc.*
FROM ManufractorCategories mc
WHERE mc.Active = 'true'
AND mc.Folder = 'false'
AND (mc.Id not in (SELECT Category_id FROM Manufractor_Category
WHERE Manufractor_id = 3));
That's my last, not working LINQ statement 那是我的最后一个不起作用的LINQ语句
(IQueryable<object>)db.ManufractorCategories
.Where(o => o.Active == active)
.Where(o => o.Folder == folder)
.Select(i => new { i.Id, i.Folder }).Except(db.Manufractor_Categories.Where(t => t.Manufractor_id == id).Select(t => new { t.Category_id })).Distinct();
I've tried the whole Sunday on that, but the Except statement won't work. 我已经尝试了整个星期天,但是Except语句不起作用。
Thanks in advances for any help! 在此先感谢您的帮助!
The Except
method requires two sets of the same type - this means that you would have to select objects of type ManufractorCategory
in the nested query as well as in the outer query - then it would select all categories that are in the first one and not in the second one. Except
方法需要两组相同类型的数据集-这意味着您必须在嵌套查询和外部查询中选择ManufractorCategory
类型的对象-然后它将选择第一个而不是第一个类别中的所有类别第二个。
An easier alternative is to use the Contains
method to check whether the current ID is in a list of IDs that you want to filter. 一个更简单的替代方法是使用
Contains
方法来检查当前ID是否在要过滤的ID列表中。 The following should work: 以下应该工作:
var q =
db.ManufractorCategories
.Where(o => o.Active == active)
.Where(o => o.Folder == folder)
.Select(i => new { i.Id, i.Folder })
.Where(o =>
!db.Manufractor_Categories
.Select(t => t.Manufractor_id)
.Contains(o.Id)
.Distinct();
And a simplified version using query syntax: 以及使用查询语法的简化版本:
var q =
from o in db.ManufractorCategories
where o.Active == active && o.Folder == folder &&
db.Manufractor_Categories
.Select(t => t.Manufractor_id)
.Contains(o.Id)
select new { i.Id, i.Folder };
The Except
statement is going to get a list of objects with the Category_id
property. Except
语句将获得具有Category_id
属性的对象列表。 However, you're query has a result that contains objects with the Id
and Folder
properties. 但是,您查询的结果中包含带有
Id
和Folder
属性的对象。 The query will most likely be unable to see where these objects are equal, and so, the Except
clause won't take effect. 该查询很可能无法看到这些对象在哪里相等,因此,
Except
子句不会生效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.