简体   繁体   中英

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. 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:

    [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:

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

@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:

 <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.

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

Ok, it seems that I found a way to update the database without using the TryUpdateModel method. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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