データベースを管理するために 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();
}
前もって感謝します。