简体   繁体   English

使用TryUpdateModel方法在ASP.NET MVC 3中使用EntityFramework更新多个对象

[英]Update multiple objects using EntityFramework in ASP.NET MVC 3 with TryUpdateModel method

I am struggling with ASP.NET MVC3 when trying to update data via Entity Framework. 在尝试通过Entity Framework更新数据时,我正在努力使用ASP.NET MVC3。 The process is as followed: 过程如下:

I have this Model: 我有这个型号:

    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; }

    }

In the controller I filter the table via a where statement to get only the entrys that match the user: 在控制器中,我通过where语句过滤表,只获得与用户匹配的entrys:

    [HttpGet]
    public ActionResult Index()
    {
        var user = User.Identity.Name;
        var model = _db.Bets.Where(t => t.Better == user);

        return View(model);
    }

The View is two parts, one that takes care of the table headers, and the other that lists all bets of the user: 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>

The EditorTemplate: 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>

Back in the controller I try to update the model: 回到控制器,我尝试更新模型:

    [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");
    }

This does absolutely nothing. 这绝对没有。 The Entity Framework won't update the database at all. 实体框架根本不会更新数据库。 I even separated the table so that the resulting bet tags in the html file will be distinguishable (note the [index] before the name value: 我甚至将表格分开,以便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" />

Can somebody tell me why the Entity Framework isn't updating the database? 有人可以告诉我为什么实体框架没有更新数据库? Is there something wrong with the object mapping? 对象映射有问题吗?

I was having the same issue before. 我之前遇到过同样的问题。 MSDN can be pretty confusing on this subject but halfway down the page states that if you are creating your POCO entities without proxycreationenabled, you will have to call detectchanges before calling savechanges. MSDN在这个问题上可能会让人感到困惑,但在页面的中间部分表示,如果您在没有proxycreationenabled的情况下创建POCO实体,则必须在调用savechanges之前调用detectchanges。

TryUpdateModel(model);
_db.DetectChanges();
_db.SaveChanges();

Ok, it seems that I found a way to update the database without using the TryUpdateModel method. 好吧,似乎我找到了一种不使用TryUpdateModel方法更新数据库的方法。 Since the items sent in the html post are distinguishable, I can add a parameter to the controller method which holds the bets I get from the view. 由于在html帖子中发送的项目是可区分的,我可以在控制器方法中添加一个参数,该方法保存从视图中获得的投注。 Then I iterate over the results from the database and update the fields that changed with the field values of the bets from the view: 然后我迭代数据库中的结果,并从视图中更新使用投注的字段值更改的字段:

    [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");
    }

I wonder if there is still a way to get it work with the TryUpdateModel method. 我想知道是否还有办法让它与TryUpdateModel方法一起工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM