【发布时间】:2015-01-20 14:12:25
【问题描述】:
我的 Web 应用程序在 Station 和 Timetable 实体之间有一个多对多链接,链接它们的实体称为 StationTimetable,它还保存有关两个实体之间链接的数据。当我创建一个新的Timetable 时,我想在数据库中创建新的(和多个)StationTimetable 条目来对应这个新的Timetable。
到目前为止,当用户创建新时间表时,我已经设法让应用程序只保存一个 StationTimetable 条目。我有点理解为什么会这样,并且我尝试对其进行修改以保存多个条目,但是据我所知,我现在遇到了障碍。
所以,我有一个 TimetablesCreateViewModel,这是我的视图使用的模型:
public class TimetablesCreateViewModel
{
public Timetable Timetable { get; set; }
public IEnumerable<StationTimetable> StationTimetables { get; set; }
public Station Station { get; set; }
public SelectList StationList { get; set; }
}
在我看来,我最多允许用户插入 10 个 StationTimetable 条目:
@for (var i = 0; i < 10; i++)
{
<tr>
<td>@Html.DropDownListFor(model => model.StationTimetables.StationId, Model.StationList, "---", htmlAttributes: new { @class = "form-control col-md-2" })</td>
<td>@Html.EditorFor(model => model.StationTimetables.Arrival, new { htmlAttributes = new { @class = "form-control" } })</td>
<td>@Html.EditorFor(model => model.StationTimetables.Departure, new { htmlAttributes = new { @class = "form-control" } })</td>
</tr>
}
然后,在我的控制器方法中,我想做如下的事情:
public ActionResult Create(TimetablesCreateViewModel viewModel)
{
if (ModelState.IsValid)
{
db.Timetables.Add(viewModel.Timetable);
// Somehow loop over viewModel.StationTimetables and add them here?
// db.StationTimetables.Add(viewModel.StationTimetable);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(viewModel);
}
直接的问题似乎是我认为DropDownListFor 和EditorFor 方法在抱怨,这是有道理的,因为我在我的视图模型中将StationTimetables 指定为IEnumerable,我可以'不要访问IEnumerable 的StationId、Arrival 和Departure 属性。这些属性是IEnumerable 持有的实体的一部分。
不幸的是,我不知道如何使用 Html 帮助器创建一个表单,在该表单中我可以使用多个 StationTimetable 实体填充 StationTimetables。如果我可以在我的Create 方法中获取多个StationTimetable 条目,我认为之后将它们添加到数据库中不会有问题。
感谢您的帮助。
【问题讨论】:
-
Timetable和Station类中是否还有其他导航属性?关于抱怨 Html 助手,也许我会在访问属性之前使用StationTimetables.ToList()。
标签: c# asp.net-mvc entity-framework many-to-many asp.net-mvc-viewmodel