虚拟属性未在数据库中更新

时间:2018-06-27 17:28:09

标签: c# asp.net-mvc entity-framework

我正在尝试编辑和更新数据库条目。除了我的虚拟财产之一之外,一切都将更新。我在做什么错了?

控制器

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Plan plan, FormCollection collection)
{
    try
    {
        using (var db = new _dbContext())
        {
            if (collection.AllKeys.Contains("PlanGroupID"))
            {
                var PlanGroupID = Int32.Parse(collection["PlanGroupID"]);
                var existingPlanGroup = db.PlanGroups.Find(PlanGroupID);
                plan.PlanGroup = existingPlanGroup;
                db.PlanGroups.Attach(existingPlanGroup);
            }

            Plan planContext = db.Plans.Find(plan.ID);
            db.Entry(planContext).CurrentValues.SetValues(plan);
            db.SaveChanges();

            return RedirectToAction("Complete");
            }
    }

    catch (Exception Ex)
    {
        return View();
    }
}

模型-虚拟属性

public virtual PlanGroups PlanGroup { get; set; }

1 个答案:

答案 0 :(得分:0)

看起来像您附加到现有计划组。

db.PlanGroups.Attach(existingPlanGroup); 

执行此操作时,实体的状态不变。

请注意,如果在不对附加实体进行任何其他操作的情况下调用SaveChanges,则不会对数据库进行任何更改。这是因为实体处于未更改状态。 https://msdn.microsoft.com/en-us/library/jj592676(v=vs.113).aspx