使用实体框架同时更新和添加子行 [英] Update and Add Child Rows at same time with Entity Framework

查看:57
本文介绍了使用实体框架同时更新和添加子行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在同时修改和添加子行时遇到麻烦。我正在使用答案中的技术: stackoverflow.com/questions/5557829 / ...

i´m having some troubles when it comes to modify and add child rows at the same time. I´m using the technique from the answer: stackoverflow.com/questions/5557829/....

问题出在以下代码中:

public void EditReport(tbl_inspection inspection)
{
    foreach (var roll in inspection.tbl_inspection_roll)
    {                    
        container.tbl_inspection_roll.Attach(roll);
        container.ObjectStateManager.ChangeObjectState(roll, (roll.id_inspection_roll == 0) ? EntityState.Added : EntityState.Modified);
    }

    container.SaveChanges();
}

我总是至少需要更新一行。当我要添加1行时,它工作正常,问题是当我尝试同时添加多于1行时,显示了众所周知的错误:

I always have at least 1 row to update. When I have 1 row to add, it works fine, the problem is when I try to add more than 1 row at the same time, shows the well-known error:


ObjectStateManager中已经存在具有相同键的对象。
ObjectStateManager无法使用相同的
键跟踪多个对象。

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

感觉像我在这里丢失了一些东西...

Feels like I´m missing something here...

推荐答案

此处的问题是因为两个或多个子存根具有相同的密钥:0。一旦尝试附加第一个对象,它将引发错误。

The problem here is because two or more child stubs have the same key: 0. Once you try to Attach the first object, it fires the error.

必须使用某种DTO重新设计该方法(我认为将ViewModel对象传递给Domain Model层是不正确的,这就是为什么我使用存根)。或直接从Controller调用添加/修改函数。

The method will have to be redesigned, using some kind of DTO (I think it's not correct to pass the ViewModel object to the Domain Model layer, thats why I was using stubs). Or calling a function to Add/Modify direct from the Controller.

编辑:

以下是代码:

public void EditReport(Inspection obj)
{
    var inspection = new tbl_inspection
    {
        id_inspection = obj.ID,
        code = obj.Code       
    };

    foreach (var roll in obj.Rolls)
    {                    
        var rollStub = new tbl_inspection_roll
        {
            id_inspection_roll = roll.ID,
            id_inspection = obj.ID,
            description = roll.Description
        };

        container.tbl_inspection_roll.Attach(roll);
        container.ObjectStateManager.ChangeObjectState(roll, (roll.id_inspection_roll == 0) ? EntityState.Added : EntityState.Modified);
    }

    container.tbl_inspection.Attach(inspection);
    container.ObjectStateManager.ChangeObjectState(inspection, EntityState.Modified);

    container.SaveChanges();
}

欢迎使用更好的解决方案...

Any better solutions are welcomed...

这篇关于使用实体框架同时更新和添加子行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆