简体   繁体   English

无法在实体框架中更新对象

[英]Can't update object in Entity Framework

I'm trying to update my table via EF 6 in my ASP.NET MVC 5 app. 我正在尝试通过ASP.NET MVC 5应用程序中的EF 6更新表。

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). 我怀疑该对象不是IQueryable ,因此无法被EF跟踪(如果我的理解正确的话)。

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) 这需要更新现有的数据库条目,当前用112进行硬编码(仅用于测试)

  2. See if the plan with ID 112 exists (it does). 查看ID为112的计划是否存在(确实存在)。 We'll name this existingPlan . 我们将其命名为existingPlan I'm expecting EF tracks any updates to this 我希望EF能够跟踪对此的任何更新

  3. Since the plan exists, call UpdatePlan , providing the newPlan and the existingPlan 由于该计划存在,请调用UpdatePlan ,以提供newPlanexistingPlan

  4. 'Map' the relevant new values from newPlan to existingPlan 将相关的新值从新newPlan “映射”到existingPlan

  5. Since EF should be tracking the existing plan (which has now been updated), simply save 由于EF应该跟踪现有计划(现已更新),因此只需保存

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. 我注意到的检索Plan实例通过发生_planQuery对象,而通过发生更新_planCommand对象。
Probably these don't share the same DbContext instance; 这些可能不会共享相同的DbContext实例。 if this is the case, the Plan instance is not being changetracked within the DbContext doing the update, so no update statement gets executed. 如果是这种情况,则在执行更新的DbContext不会跟踪Plan实例,因此不会执行更新语句。

To solve, ensure that both retrieval and update occur via the same DbContext instance. 要解决,请确保通过相同的DbContext实例进行检索和更新。

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

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