尝试通过实体框架更新数据时,我正在努力使用 ASP.NET MVC3。过程如下:
我有这个模型:
public class Bet
{
public string BetID { get; set; }
public int FixtureID { get; set; }
public string Better { get; set; }
public int GoalsHome { get; set; }
public int GoalsGuest { get; set; }
public virtual Fixture { get; set; }
}
在控制器中,我通过 where 语句过滤表以仅获取与用户匹配的条目:
[HttpGet]
public ActionResult Index()
{
var user = User.Identity.Name;
var model = _db.Bets.Where(t => t.Better == user);
return View(model);
}
视图由两部分组成,一个负责处理表格标题,另一个列出用户的所有投注:
<fieldset>
<legend>Bets</legend>
<table>
<tr>
<th>
Kickoff
</th>
<th>
Home Team
</th>
<th>
Guest Team
</th>
<th>
Group
</th>
<th>
Bet
</th>
</tr>
@Html.EditorFor(m => m) //this is resolved in an self made EditorTemplate
</table>
编辑器模板:
@model Betting.Models.Bet
<tr>
<td>
@Html.DisplayFor(modelItem => Model.Fixture.Kickoff)
</td>
<td>
@Html.DisplayFor(modelItem => Model.Fixture.HomeTeam)
</td>
<td>
@Html.DisplayFor(modelItem => Model.Fixture.GuestTeam)
</td>
<td>
@Html.DisplayFor(modelItem => Model.Fixture.Group)
</td>
<td>
@Html.TextBoxFor(modelItem => Model.GoalsHome, new { style = "width: 30px" }):
@Html.TextBoxFor(modelItem => Model.GoalsGuest, new { style = "width: 30px" })
</td>
@Html.HiddenFor(modelItem => Model.FixtureID)
</tr>
回到控制器中,我尝试更新模型:
[HttpPost]
public ActionResult Index(FormCollection collection)
{
var user = User.Identity.Name;
var model = _db.Bets.Where(t => t.Better == user);
TryUpdateModel(model);
_db.SaveChanges();
return RedirectToAction("Index");
}
这绝对没有任何作用。实体框架根本不会更新数据库。我什至将表格分开,以便在 html 文件中生成的 bet 标签可以区分(注意名称值之前的 [index]:
<input data-val="true" data-val-number="The field GoalsHome must be a number." data-val-required="The GoalsHome field is required." name="[1].GoalsHome" style="width: 30px" type="text" value="3" />:
<input data-val="true" data-val-number="The field GoalsGuest must be a number." data-val-required="The GoalsGuest field is required." name="[1].GoalsGuest" style="width: 30px" type="text" value="0" />
有人能告诉我为什么实体框架不更新数据库吗?对象映射有问题吗?