我有一个用户表和一个组表,一个用户可以成为许多组的一部分
[USERID]----*-[USERID GROUPID]-*-----[GROUPID]
(join table)
public partial class user
{
public int user_id { get; set; }
public string name { get; set; }
public virtual ICollection<group> groups{ get; set; }
}
public partial class group
{
public int user_id { get; set; }
public string name { get; set; }
public virtual ICollection<user> users{ get; set; }
}
1)我需要返回属于特定组的所有用户
var queryable = (from g in db.groups
where g.group_id == id
select g.users)
.ToList()
.Select(u => new {
id = u.id, //Error does not contain definition for id
name = u.name //Error does not contain definition for name
});
2)我需要返回属于特定组的特定用户
感谢您的建议
答案 0 :(得分:1)
我需要返回属于特定组的所有用户
Lambda语法:
db.groups.Where(g => g.group_id == id).SelectMany(g => g.users)
或查询语法:
from g in db.groups
where g.group_id == id
from u in g.users
select u
我需要返回属于特定群组的特定用户
就像上面的查询一样,还有一个额外的过滤器
db.groups.Where(g => g.group_id == id)
.SelectMany(g => g.users)
.Where(u => u.id == userId)
查询语法:
from g in db.groups
where g.group_id == id
from u in g.users
where u.id == userId
select u
答案 1 :(得分:0)
尝试这样的事情:
var queryable = (from p in db.plants
join u in db.users on p.userId equals u.id
where p.plant_id == plant_id
select u)
.ToList()
.Select(u => new {
id = u.id,
name = u.name
});
其中p.userId是连接工厂和用户表的列
答案 2 :(得分:0)
var queryable = (from p in db.plants
join u in db.users on p.userId equals u.id
where p.plant_id == plant_id
select new { p.id, p.name, u.name}).ToList();