我有一个项目,我使用 EntityFramework Code First 来管理数据库。我为此使用的模型如下:
[Table("Data")]
public class Data
{
[Key, Column("Id")]
public int Id { get; set; }
[Column("Code")]
public string Code { get; set; }
[Column("Name")]
public string Name { get; set; }
[Column("Description")]
public string Description { get; set; }
public virtual List<DataAttribute> Attributes { get; set; }
}
和
[Table("DataAttribute")]
public class DataAttribute
{
[Key, Column("Id")]
public int Id { get; set; }
[Column("IdData"), ForeignKey("Data")]
public int IdData { get; set; }
[Column("Name")]
public string Name { get; set; }
[Column("Description")]
public string Description { get; set; }
public virtual Data Data { get; set; }
}
我遇到的问题是当我尝试编辑 Data 对象(及其相关的 DataAttribute 值)时。在提交包含 Data 元素和 DataAttribute 元素的表单时,我没有正确映射它。我举一个 .cshtml 文件的例子。
@model MVCTestApp.Models.Data
@{
ViewBag.Title = "Edit";
}
@section Scripts {
<script type="text/javascript">
$(function () {
$('#new-row').click(function () {
$('table tbody').append(
'<tr>' +
'<td><input class="name" type="text" /></td>' +
'<td><input class="description" type="text" /></td>' +
'<td><a class="delete" href="#">Delete</a></td>' +
'</tr>'
);
$('.delete').click(function () {
$(this).parent().parent().remove();
});
});
});
</script>
}
@using (@Html.BeginForm("Edit", "Data", FormMethod.Post)) {
@Html.HiddenFor(a => a.Id)
Name:
<br />
@Html.TextBoxFor(a => a.Name)
<br />
Description:
<br />
@Html.TextBoxFor(a => a.Description)
<br />
Code:
<br />
@Html.TextBoxFor(a => a.Code)
<br />
<table>
<thead>
<tr>
<th>
Name
</th>
<th>
Description
</th>
<th>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a id="new-row" href="#">New Row</a>
</td>
<td colspan="2">
</td>
</tr>
@if (Model != null) {
foreach (var item in Model.Attributes) {
<tr>
@Html.HiddenFor(b => item.Id)
@Html.HiddenFor(b => item.IdData)
<td class="name">@Html.TextBoxFor(b => item.Name)
</td>
<td class="description">@Html.TextBoxFor(b => item.Description)
</td>
<td>
<a class="delete" href="#">Delete</a>
</td>
</tr>
}
}
</tbody>
</table>
<input type="submit" value="submit" />
}
问题是这样的。
发布时如何让 EntityFramework 识别控制器上的 DataAttributes 列表?
这是我现在正在使用的代码。
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Data model)
{
if (model != null) {
db.Data.Add(model); //model has the model.Attributes list set as null
db.SaveChanges();
return View("Index", db.Data.OrderBy(a => a.Id).ToList());
}
return View();
}
先感谢您。