Linq查询带有双子查询

时间:2014-05-13 16:57:19

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

我正在努力转换我写入Linq的以下SQL查询。我想我走在正确的轨道上,但我必须错过一些东西。

我现在得到的错误是:

  

System.Linq.IQueryable不包含.Contains

的定义

这对我来说很困惑,因为它应该对吗?

SQL

select Users.*
from Users
where UserID in (select distinct(UserID)
                        from UserPermission
                        where SupplierID in (select SupplierID
                                             from UserPermission
                                             where UserID = 6))

LINQ

var Users = (from u in _db.Users
             where (from up in _db.UserPermissions select up.UserID)
               .Distinct()
               .Contains((from up2 in _db.UserPermissions
                          where up2.UserID == 6
                          select up2.SupplierID))
             select u);

编辑:我最终回到了SqlCommand对象,因为这是我今天必须完成的事情,不能浪费太多时间试图找出如何以正确的方式做到这一点Linq和EF。我讨厌代码黑客:(

3 个答案:

答案 0 :(得分:1)

我认为这里没有必要distinct(也许我错了)。但这里有一个更简单的版本(假设您已正确定义了所有导航属性)

var lstUsers = DBContext.Users.Where(
                    x => x.UserPermissions.Any(
                                    y => y.Suppliers.Any(z => z.UserID == 6)
                                            )
                                    ).ToList();

如果您在UserID实体中有Supplier字段,则在上方,如果不是,您可以再次使用导航属性,

var lstUsers = DBContext.Users.Where(
                    x => x.UserPermissions.Any(
                                    y => y.Suppliers.Any(z => z.User.UserID == 6)
                                            )
                                    ).ToList();

答案 1 :(得分:0)

Contains()只需要一个元素,因此它不会像你编写的那样工作。试试这个替代:

var Users = _db.Users
            .Where(u => _db.UserPermissions
                .Select(x => UserID)
                .Distinct()
                .Where(x => _db.UserPermissions
                    .Where(y => y.UserID == 6)
                    .Select(y => y.SupplierID)
                    .Contains(x))
                );

答案 2 :(得分:0)

我没有尝试过,但您可以尝试使用let关键字:

var Users = (from u in _db.Users
             let distinctUsers = (from up in _db.UserPermissions select up).Distinct()
             let subQuery = (from up2 in _db.UserPermissions
                          where up2.UserID == 6
                          select up2)
             where 
             distinctUsers.SupplierID== subQuery.SupplierID && 
             u.UserID==distinctUsers.UserID
             select u);