简体   繁体   English

如何附加包含n到n关系的对象?

[英]How to attach an object that contains a n to n relation?

I have two tables that are linked nn . 我有两个链接nn表。 And I have a method that takes one object and saves. 我有一个方法,需要一个对象并保存。

public int Save(Table1 element)
{
    using (var database = new Entities())
    {
        if (element.ID == 0)
        {
            database.Table1.AddObject(element);
        }
        else
        {
            database.Attach(element); //
            database.ObjectStateManager.GetObjectStateEntry(element).SetModified();
            database.Refresh(RefreshMode.ClientWins, element);
        }

        return database.SaveChanges();
    }
}

When I don't try to modify obj1.Table2 it attaches and saves successfully. 当我不尝试修改obj1.Table2它会成功附加并保存。 But if I try to modify this EntityCollection 但是,如果我尝试修改此EntityCollection

element.Table2.Add(tb2);

And save, I get the following error: 并保存,我收到以下错误:

An object with a temporary EntityKey value cannot be attached to an object context. 具有临时EntityKey值的对象无法附加到对象上下文。

at Line: database.Attach(element); at Line: database.Attach(element);

How can I fix it? 我该如何解决?


Database: 数据库:

Table 1             Table 2
ID | Name           ID | Name
---------           -------------------
 1 | One             1 | Related to One
 2 | Two             2 | Related to One
 3 | Three

            Table 3
            Tb1 | Tb2
            ---------
//            1 | 1
//            1 | 2

Creating Table1 object: 创建Table1对象:

var element = GetTable1Obj(1);

element.Table2.Add(GetTable2Obj(1)); // GetTable2Obj uses a separated context
element.Table2.Add(GetTable2Obj(2)); // like Save method to return the object

provider.Save(element); // Method above

在此输入图像描述

If Your Entity frame work model is set to something like this You should be able to modify t1 or t2 without having issues. 如果您的实体框架工作模型设置为这样的东西您应该能够修改t1或t2而不会出现问题。 while still keeping 同时仍然保持

From the looks of table 3 in your example you don't have a key for the entries. 从示例中的表3的外观来看,您没有条目的键。 Which will cause issues when modifying the Entity Object. 修改实体对象时会出现问题。 What is your DB Fk set at. 你的DB Fk是什么设置的。

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

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