简体   繁体   English

实体框架 - 关系未更新

[英]Entity framework - Relation not updating

I am having issues with updating the relation between two entities when editing one of them.在编辑其中一个实体时,我在更新两个实体之间的关系时遇到问题。 Please note that I am using Entity Framework 4.0.请注意,我使用的是实体框架 4.0。

Very basically, a Category needs to belong to a Department (one Department to many Categories ).基本上,一个Category需要属于一个Department (一个Department到多个Categories )。

I implemented the following directly into the Category model:我直接在Category模型中实现了以下内容:

public void Save()
{
    using (var db = new MyDatabase())
    {
        if (this.id > 0)
        {
            db.Categories.Attach(this);
            db.ObjectStateManager.ChangeObjectState(this, EntityState.Modified);
        }
        else
        {
            db.Categories.AddObject(this);
        }

        db.SaveChanges();
    }
}

public int DepartmentID
{
    get
    {
        if (this.DepartmentReference.EntityKey == null) return 0;
        else return (int)this.DepartmentReference
            .EntityKey.EntityKeyValues[0].Value;
    }
    set
    {
        this.DepartmentReference.EntityKey
           = new EntityKey("MyDatabase.Departments", "Id", value);
    }
}

Creating an object works without issue, it's only when I try to save an edited item that the issue occurs (so the issue lies within the if (this.id > 0) block).创建对象没有问题,只有当我尝试保存已编辑的项目时才会出现问题(因此问题出在if (this.id > 0)块内)。

I am aware that EntityState.Modified only applies to scalar values.我知道EntityState.Modified仅适用于标量值。 The above snippet is a slightly older version.上面的代码片段是一个稍旧的版本。 I have already tried to fix it in numerous ways, but none of these have solved the problem.我已经尝试以多种方式修复它,但这些都没有解决问题。

I found numerous solutions on Stackoverflow, but none of them worked.我在 Stackoverflow 上找到了很多解决方案,但都没有奏效。 See below for snippets of my previous attempts.请参阅下面的我以前尝试的片段。

I checked the values in debug, the current item's Department and DepartmentID fields correctly hold the changed value.我检查了调试中的值,当前项目的DepartmentDepartmentID字段正确保存了更改后的值。 Before the attaching, after the attaching, all the way through.贴前,贴后,一路走过去。 But Entity Framework is ignoring these changes, while still correctly doing the scalar value adjustments.但是实体框架忽略了这些更改,同时仍然正确地进行了标量值调整。

What am I missing?我错过了什么? If anyone could point me in the right direction?如果有人能指出我正确的方向吗?

The things I tried include:我尝试的事情包括:

//First try
if (this.id > 0)
{
    var department = db.Departments.Single(x => x.Id == this.DepartmentID);

    db.Categories.Attach(this);

    this.Department = department;

    db.ObjectStateManager.ChangeObjectState(this, EntityState.Modified);
}

//Second try
if (this.id > 0)
{
    db.Categories.Attach(this);
    db.Departments.Attach(this.Department);

    db.ObjectStateManager.ChangeObjectState(this, EntityState.Modified);
}

//Third try
if (this.id > 0)
{
    var department = db.Departments.Single(x => x.Id == this.DepartmentID);

    db.Categories.Attach(this);

    this.DepartmentID = department.Id;

    db.ObjectStateManager.ChangeObjectState(this, EntityState.Modified);
}

//Fourth try
if (this.id > 0)
{
    var departmentID = this.DepartmentID;

    db.Categories.Attach(this);

    this.Department = db.Departments.Single(x => x.Id == departmentID);

    db.ObjectStateManager.ChangeObjectState(this, EntityState.Modified);
}

Update更新

As requested, here's how the .Save() method is being called.根据要求,以下是.Save()方法的调用方式。 Please note that the actual web form has been build using TextBoxFor() etc. so the modelbinding is okay.请注意,实际的 Web 表单是使用TextBoxFor()等构建的,因此模型绑定是可以的。 This exact same method is also used for the creation of the categories, which does work as intended.这种完全相同的方法也用于创建类别,它按预期工作。

    public JsonResult SaveCategory(Category category)
    {
        try
        {
            category.Save();

            return Json(category.toJson(), JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Json("ERROR", JsonRequestBehavior.AllowGet);
        }
    }

您必须在修改实体后调用db.SaveChanges()

I managed to find the issue.我设法找到了问题。 This was not an easy one.这不是一件容易的事。

I noticed that most of my relations created a Scalar value to the 'child' entity.我注意到我的大多数关系都为“子”实体创建了一个标量值。 (Eg Category shoud have automatically received a DepartmentID scalar value). (例如, Category应该自动收到一个DepartmentID标量值)。 But this was not the case.但事实并非如此。

Here's the issue: if you create the association in EF, you get a window asking you to choose which two entities you want to associate.问题是:如果您在 EF 中创建关联,您会看到一个窗口,要求您选择要关联的两个实体。 The child (Category, one) needs to be in the right field, while the parent (Department, many) needs to be on the left.孩子(类别,一)需要在正确的领域,而父母(部门,许多)需要在左边。 The menu allows you to place them either side, there is nothing preventing you from doing this.菜单允许您将它们放在两侧,没有什么可以阻止您这样做。 But only if you enter the data one <-> many you will get the scalar value added.但只有当您输入一个 <-> 多个数据时,您才会获得添加的标量值。 Not when you put it like many <-> one> even though that should be literally the same thing.不是当你把它像many <-> one> 一样时,即使这应该是同一个东西。

Am I right in stating that this is a bug?我说这是一个错误是否正确?

My original snippet, which only does the .Attach() and EntityState.Modified now works as expected.我原来的片段,它只执行.Attach()EntityState.Modified现在按预期工作。

I can only mark this answer as correct in 2 days, but you can consider this question as closed.我只能在 2 天内将此答案标记为正确,但您可以认为此问题已结束。

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

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