[英]Update multiple objects using EntityFramework in ASP.NET MVC 3 with TryUpdateModel method
在尝试通过Entity Framework更新数据时,我正在努力使用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语句过滤表,只获得与用户匹配的entrys:
[HttpGet]
public ActionResult Index()
{
var user = User.Identity.Name;
var model = _db.Bets.Where(t => t.Better == user);
return View(model);
}
View是两部分,一部分负责表头,另一部分列出用户的所有赌注:
<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>
EditorTemplate:
@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文件中的结果下注标签可以区分(注意名称值之前的[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" />
有人可以告诉我为什么实体框架没有更新数据库? 对象映射有问题吗?
我之前遇到过同样的问题。 MSDN在这个问题上可能会让人感到困惑,但在页面的中间部分表示,如果您在没有proxycreationenabled的情况下创建POCO实体,则必须在调用savechanges之前调用detectchanges。
TryUpdateModel(model);
_db.DetectChanges();
_db.SaveChanges();
好吧,似乎我找到了一种不使用TryUpdateModel方法更新数据库的方法。 由于在html帖子中发送的项目是可区分的,我可以在控制器方法中添加一个参数,该方法保存从视图中获得的投注。 然后我迭代数据库中的结果,并从视图中更新使用投注的字段值更改的字段:
[HttpPost]
public ActionResult Index(FormCollection collection, List<Bet> bets)
{
var user = User.Identity.Name;
var model = _db.Bets.Where(t => t.Better== user);
int i = 0;
foreach (var bet in model)
{
Bet the_Bet= bets.Find(
delegate(Bet _bet)
{
return _bet.BetID == bet.BetID;
});
bet.GoalsHome= the_Bet.GoalsHome;
bet.GoalsGuest= the_Bet.GoalsGuest;
i++;
}
_db.SaveChanges();
return RedirectToAction("Index");
}
我想知道是否还有办法让它与TryUpdateModel方法一起工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.