简体   繁体   中英

Can't update object in Entity Framework

I'm trying to update my table via EF 6 in my ASP.NET MVC 5 app.

I get no error message or exception, but nothing is saved to the database. I suspect the object isn't IQueryable and as such not tracked by EF (if my understanding is right).

public async Task Work(Plan newPlan)
{
    var existingPlan = await this._planQuery.GetPlan(112);

    if (existingPlan != null)
    {
        await this._planCommand.UpdatePlan(newPlan, existingPlan))
    }
}

And the 2 relevant methods are

internal async Task<Plan> GetPlan(int id)
{
    return await base.DataContext.Plans.SingleAsync(a => a.Id == id);
}

internal async Task<bool> UpdatePlan(Plan newPlan, Plan existingPlan)
{
    existingPlan.LastEditDate = DateTime.Now;
    existingPlan.PlanName = newPlan.PlanName;
    existingPlan.Website = newlan.Website;

    if (!await base.SaveToDatabase())
        return false;

     return true;
}

This is what I'm doing, and if I understand correct what I'm expecting:

  1. Receive an object with various property values. This needs to update an existing database entry, currently hardcoded with 112 (for testing only)

  2. See if the plan with ID 112 exists (it does). We'll name this existingPlan . I'm expecting EF tracks any updates to this

  3. Since the plan exists, call UpdatePlan , providing the newPlan and the existingPlan

  4. 'Map' the relevant new values from newPlan to existingPlan

  5. Since EF should be tracking the existing plan (which has now been updated), simply save

What am I missing here?

I notice that the retrieval of the Plan instance occurs via a _planQuery object, whereas the update occurs via a _planCommand object.
Probably these don't share the same DbContext instance; if this is the case, the Plan instance is not being changetracked within the DbContext doing the update, so no update statement gets executed.

To solve, ensure that both retrieval and update occur via the same DbContext instance.

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