更好的方法来执行此LINQ查询

时间:2015-05-06 13:48:15

标签: c# linq

我正在使用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);
}

2 个答案:

答案 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)

我假设您在RoomsPeoplePeople之间有导航属性。如果存在,我会使用流畅的语法重写它,而不是弄乱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来电,我必须尝试确认。