Linq查询涉及多对多的关系

时间:2014-08-15 14:37:06

标签: linq entity-framework visual-studio-2012

我正在尝试编写LINQ查询但不知何故它不起作用,这里是查询

var Table3Qry =
   from LoginTable in db.Logins 
   from ServerTable in LoginTable.Servers.Where(x => x.ServerID == id) 
   select new { LoginTable.passwd, LoginTable.LoginID };

表结构

Login

 - Passwd
 - Userid 
 - Loginid

Server

 - Serverid
 - Servername

ServerLogins

 - Serverid
 - Loginid

我想在Password表中找到特定Login(查询中名为ServerID)的所有id

1 个答案:

答案 0 :(得分:1)

按ID过滤服务器,然后从每个服务器登录中选择所有密码:

var passwords =
     db.Servers.Where(s => s.ServerID == id)
       .SelectMany(s => s.Logins.Select(l => new { l.Passwd, l.LoginId }));

查询语法:

var passwords = from s in db.Servers
                where s.ServerID == id
                from l in s.Logins
                select new { l.Passwd, l.LoginId };

如果您从登录表开始:

var passwords = from l in db.Logins
                where l.Servers.Any(s => s.ServerID == id)
                select new { l.Passwd, l.LoginId };