我有三个表多对多关系我加入了三个表并选择了我想要的值但现在我需要从查询结果中选择一行,通过指定id这是我的三个
[HttpPost]
public JsonResult Getdata(string batchcode)
{
//var studentid = (from a in db.Studentassignbatches
// where a.batch_code == batchcode
// select new { a.UserId });
//var id = db.UserDetails.Where(a => a.UserId.Equals(db.Studentassignbatches.Where(x => x.batch_code.Equals(batchcode)).Select(x => x.UserId))).Select(a => a.id);
var id = db.UserDetails
.Join(db.Studentassignbatches,
x => x.UserId, y => y.UserId,
(x, y) => new { x, y })
.Where(c => c.y.batch_code == batchcode)
.Select(d => new UserDetail
{
id = d.x.id
});
return Json(id, JsonRequestBehavior.DenyGet);
}
结果将类似于使用sql查询
sql查询
select UserDetails.id
from UserDetails
inner join
Studentassignbatches on
Studentassignbatches.UserId=UserDetails.UserId
where
Studentassignbatches.batch_code = 'CCNA Security-1';
如果多个则会显示多个结果。
我不明白我做了什么错。 或者只是因为使用lambda表达式我没有得到我的结果?不使用linq ??? 请帮忙吗?
答案 0 :(得分:2)
当ORM为您完成此操作时,为什么加入会感到过于复杂......
[HttpPost]
public JsonResult Getdata(string batchcode)
{
var detailIds = db.UserDetails
.Where(d => d.User.Studentassignbatches.Any(b => b.batch_code == batchcode))
.Select(d => d.id)
.ToList();
return Json(detailIds, JsonRequestBehavior.DenyGet);
}
另外,如前所述,这种模式毫无意义。