如何将此Sql查询转换为Linq?

时间:2015-10-06 09:09:10

标签: sql linq contains translate

我有两张桌子:

User
  (
   UserId int primary key,
   Firstname,
   Lastname, ...
   info ...
  )

Friend
  (
   User1Id int,
   User2Id int,
   Status varchar(1), -- '1' is friend, '0' is pending friend request
   primary key(User1Id,User2Id)
  )

(User1Id, User2Id)是引用[User]表的外键。

我有这个SQL查询:

select * from User
where UserId in
(
  (select User1Id from Friend where User2Id='@id' and Status='1') 
   union
  (select User2Id from Friend where User1Id='@id' and Status='1')
)

它成功执行并按预期返回数据。

但是在从SQL转换为Linq时,我遇到了in的问题。我无法使用.Contains(),因为无法转换数据类型。我怎么翻译呢?

我试过这个Linq代码:

var query = (from u in Users 
             where u.UserId.Contains(
                 (from f in Friends 
                  where f.User1Id==1 && Status=='1' 
                  select f.User2Id
                 ).Union(from f in Friends 
                         where f.User2Id==1 && Status=='1' 
                         select f.User1Id))
             select u );

但是我收到了这个错误:

  

.Contains()不能与Int和IQuery一起使用

1 个答案:

答案 0 :(得分:1)

  internal class Program
    {
        private static void Main(string[] args)
        {
            List<User> users = new List<User>();
            users.Add(new User() { id = 1, name = "1" });
            users.Add(new User() { id = 2, name = "2" });
            users.Add(new User() { id = 3, name = "3" });

            List<Friend> friends = new List<Friend>();
            friends.Add(new Friend() { User1Id = 2, User2Id = 1 });
            friends.Add(new Friend() { User1Id = 1, User2Id = 3 });
            friends.Add(new Friend() { User1Id = 2, User2Id = 3 });

              var query = users.Where(q => (from f1 in friends where`f1.User1Id == 1 select f1.User2Id).Union(from f1 in friends where f1.User2Id ==` 1 select f1.User1Id).Contains(q.id));
        }
    }

    public class User
    {
        public int id { get; set; }

        public string name { get; set; }
    }

    public class Friend
    {


        public int User1Id { get; set; }

        public int User2Id { get; set; }
    }