我正在使用LINQ查询DbContext以获取留在特定房间的人的ID。之后,我再次使用LINQ从Person
表中使用People
获取foreach person
,其ID匹配并将其添加到我的Person
列表中,因为我的viewmodel需要它。我确信有一个更好的方式来写这个任何建议将不胜感激。
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Room room = db.Rooms.Find(id);
if (room == null)
{
return HttpNotFound();
}
List<Person> pList = new List<Person>();
var query = (from c in db.RoomsPeople
where c.RoomID == room.ID
select c).ToList();
foreach(RoomPerson r in query)
{
var asdf =(from c in db.People
where c.ID == r.PersonID
select c).ToList();
pList.Add(asdf[0]);
}
NewMvc.ViewModels.RoomPerson rp = new NewMvc.ViewModels.RoomPerson();
rp.Room = room;
rp.People = pList;
return View(rp);
}
答案 0 :(得分:3)
在两个表之间创建内部联接:
var peopleInRoom = (from roomsPeople in db.RoomsPeople
join people in db.People on roomsPeople.PersonID equals people.ID
where roomsPeople.RoomID == room.ID
select people).ToList();
答案 1 :(得分:0)
我假设您在RoomsPeople
和People
之间有导航属性。如果存在,我会使用流畅的语法重写它,而不是弄乱LINQ奇怪的连接语法。
var list = db.RoomsPeople
.Include(rp => rp.People)
.Where(rp => rp.RoomID == room.ID)
.Select(rp => new NewMvc.ViewModels.RoomPerson()
{
Room = rp,
People = rp.People
}
.ToList();
您甚至可能不需要.Include
来电,我必须尝试确认。