本文介绍了在多对多数据库Sql Server中的过渡表中添加项目和更新关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 这是一个错误的模型,没有关联A-B之间的多少。更正在EDIT2 - A 存在于数据库中, B 存在于数据库中。 我只需要输入新的 C 元素与一些Properties1和Properties2(和更新的集合 C 在已存在 A 和 B 元素) 我尝试了很多选项,例如这个,但仍然有些错误(ObjectOCntext和存在的Key等) void SaveNewC(C newC) { using(var context = new MyEntities(connectionString)) { var dbA = context.A.Where(a => a.Id == newC.A.Id ).SingleOrDefault(); var dbB = context.B.Where(b => b.Id == newC.B.Id).SingleOrDefault(); newC.A = dbA; newC.B = dbB; context.AddObject(newC); context.SaveChanges(); } } 编辑 我得到的异常:ObjectStateManager中已经存在具有相同键的对象,ObjectStateManager无法跟踪具有相同键的多个对象。 EDIT2 更新模型 解决方案您是否需要连接表映射?如果你所有想要的都是从A-> B的许多人,你可以用一个简单的方式来做。 如果你创建了C表作为一个真正的连接 - 有一个FK到A和B设置它的sql在sql这样: 然后当您从模型创建您的edmx时,将创建以下内容: 现在,在你的代码中,如果你想添加一个关系,你只需将它添加到你的集合中,EF就会自动为你的C表创建关系: var A = new A(); var b = new B(); var b2 = new B(); A.B.Add(b); A.B.Add(b2); --here was wrong model without association manyTOmany between A-B. corrected is in EDIT2--A exists in database, B exists in database.I need only enter new C element with some Properties1 and Properties2 (and update collections of C in existed A and B elements)I tried many options, like for example this, but still somethings wrong (with ObjectOCntext and existed Key etc)void SaveNewC(C newC){ using (var context = new MyEntities(connectionString)) { var dbA = context.A.Where(a => a.Id == newC.A.Id).SingleOrDefault(); var dbB = context.B.Where(b => b.Id == newC.B.Id).SingleOrDefault(); newC.A = dbA; newC.B = dbB; context.AddObject(newC); context.SaveChanges(); }}EDITException that I get: "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."EDIT2updated model 解决方案 Do you need to have the junction table mapped? If all your wanting is a Many to Many from A->B you could do it in a simpler way.If you created the C table as a true junction - and have a FK to A and B set to it's PK in sql like this:Then when you create your edmx from the model it will create this:Now, in your code if you wanted to add a relationship, you would simply add it to your collection, and EF will automatically create the relationship in your C table for you: var A = new A(); var b = new B(); var b2 = new B(); A.B.Add(b); A.B.Add(b2); 这篇关于在多对多数据库Sql Server中的过渡表中添加项目和更新关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-30 06:33