MVC - 如何在控制器中检索多条记录

MVC - how to retrieve multiple records in a controller

我有以下操作:

public ActionResult Details(string id)
{
    MyRecordContext rc = new MyRecordContext(); 
    MyRecord r = rc.MyRecords.Single(x => x.RecordID == _id);

    return View(r);
 }

但发现有多个记录具有相同的id(table的主键是组合键)。所以我需要检索一个MyRecord类型的List,所以我把代码改成了:

public ActionResult Details(string id)
{
    MyRecordContext rc = new MyRecordContext(); 
    List<MyRecord> rl = rc.MyRecords.Any(x => x.RecordID == id);

    return View(rl);
 }

但是上述显然是不正确的,因为方法 Any returns bool。有人可以帮我更正我的代码吗?

在 Linq 中,Any just returns a true/false is any of the values match. You are looking for a simple Where:

List<MyRecord> rl = rc.MyRecords.Where(x => x.RecordID == id);
public ActionResult Details(String id)
{
    MyRecordContext rc = new MyRecordContext();
    List<MyRecord> rl = rc.MyRecords.Where(x => x.RecordID == id).ToList();

    return View(rl);
}

这将 return 与 RecordID == id 的所有匹配项,然后将此列表传递给您的视图。只需确保您也更新 Details 视图以接受 List<MyRecord> 而不是 MyRecord (现在您正在传递一个集合)。