我无法弄清楚如何使用实体框架更新我的导航属性。我使用了数据库优先方法并设置了所有适当的 FK 关系。这是我正在使用的两个表的样子:
费率概况
- RateProfileID
- 个人资料名称
速度
- 费率ID
- RateProfileID (FK)
- 我要更新的其他几个属性
一个 RateProfile 可以/将有多个 Rates。我为 RateProfile 构建了我的编辑页面,以显示 RateProfile 实体及其所有关联的 Rate 实体的编辑器,并将所有这些都粘贴在带有提交按钮的表单中。我可以很好地显示所有内容,但我的更改只会持续存在于模型类 (RateProfile) 而不是它的导航属性 (Rates)。
下面是我的视图/HttpPost 编辑/模型在我的 HttpPost 编辑方法中,您可以看到我在模型的导航属性 Rates 中循环和更新每条记录的微弱尝试。
@model PDR.Models.RateProfile
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>RateProfile</legend>
@Html.HiddenFor(model => model.RateProfileID)
@Html.HiddenFor(model => model.LoginID)
<div class="editor-label">
@Html.LabelFor(model => model.ProfileName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ProfileName)
@Html.ValidationMessageFor(model => model.ProfileName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.isDefault)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.isDefault)
@Html.ValidationMessageFor(model => model.isDefault)
</div>
<div>
<fieldset>
<legend>Dime</legend>
<table>
<tr>
<th>
Min
</th>
<th>
Max
</th>
<th>
Price
</th>
<th></th>
</tr>
@foreach (var rate in Model.Rates)
{
<tr>
<td>
@Html.EditorFor(modelItem => rate.minCount)
@Html.ValidationMessageFor(model => rate.minCount)
</td>
<td>
@Html.EditorFor(modelItem => rate.maxCount)
@Html.ValidationMessageFor(model => rate.maxCount)
</td>
<td>
@Html.EditorFor(modelItem => rate.Amount)
@Html.ValidationMessageFor(model => rate.Amount)
</td>
</tr>
}
</table>
</fieldset>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
[HttpPost]
public ActionResult Edit(RateProfile rateprofile)
{
if (ModelState.IsValid)
{
db.Entry(rateprofile).State = EntityState.Modified;
foreach (Rate rate in rateprofile.Rates)
{
db.Entry(rate).State = EntityState.Modified;
}
db.SaveChanges();
return RedirectToAction("Index");
}
return View(rateprofile);
}
public partial class Rate
{
public int RateID { get; set; }
public int RateProfileID { get; set; }
public string Size { get; set; }
public decimal Amount { get; set; }
public int minCount { get; set; }
public int maxCount { get; set; }
public int PanelID { get; set; }
public virtual Panel Panel { get; set; }
public virtual RateProfile RateProfile { get; set; }
}
public partial class RateProfile
{
public RateProfile()
{
this.Rates = new HashSet<Rate>();
}
public int RateProfileID { get; set; }
public string ProfileName { get; set; }
public int LoginID { get; set; }
public bool isDefault { get; set; }
public virtual Login Login { get; set; }
public virtual ICollection<Rate> Rates { get; set; }
}