C# 无法定义两个对象之间的关系,因为它们附加到不同的 ObjectContext 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15274539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects
提问by Steve
I've read some questions/answers that have to do with this particular error message, but I'm not quite understanding the appropriate solution.
我已经阅读了一些与此特定错误消息有关的问题/答案,但我不太了解适当的解决方案。
I've read many times that you should create the EF4 context, use it, then dispose of it. Throughout my application, I'm loading entities here and there using different context objects, and then eventually want to associate the entities together.
我已经多次阅读您应该创建 EF4 上下文,使用它,然后处理它。在我的整个应用程序中,我使用不同的上下文对象在这里和那里加载实体,然后最终希望将这些实体关联在一起。
I've create a simple console application that easily causes the error. The very simple model is diagrammed followed by the code.
我创建了一个简单的控制台应用程序,它很容易导致错误。绘制了非常简单的模型,然后是代码。
How can I get the two different entities to share the same context? Do I really have to create a new context, load the two entities again (even though I already have them), simply to associate them and save?
如何让两个不同的实体共享相同的上下文?我真的必须创建一个新的上下文,再次加载这两个实体(即使我已经有了它们),只是为了关联它们并保存?
If I simply missed an already existing, appropriate question/answer, please point me to the right place.
如果我只是错过了一个已经存在的、合适的问题/答案,请把我指向正确的地方。
internal class Program {
private static void Main(string[] args) {
DeleteAllEntities();
CreateInitialEntities();
Owner o = LoadOwner();
Child c = LoadChild();
AssociateAndSave(o, c);
}
private static void AssociateAndSave(Owner o, Child c) {
using (var context = new ModelEntities()) {
// Exception occurs on the following line.
o.Children.Add(c);
context.Attach(o);
context.SaveChanges();
}
}
private static Owner LoadOwner() {
using (var context = new ModelEntities()) {
return ((from o in context.Owners
select o).First());
}
}
private static Child LoadChild() {
using (var context = new ModelEntities()) {
return ((from c in context.Children
select c).First());
}
}
private static void CreateInitialEntities() {
using (var context = new ModelEntities()) {
Owner owner = new Owner();
Child child = new Child();
context.Owners.AddObject(owner);
context.Children.AddObject(child);
context.SaveChanges();
}
}
private static void DeleteAllEntities() {
using (var context = new ModelEntities()) {
List<Child> children = (from c in context.Children
select c).ToList();
foreach (var c in children)
context.Children.DeleteObject(c);
List<Owner> owners = (from o in context.Owners
select o).ToList();
foreach (var o in owners)
context.Owners.DeleteObject(o);
context.SaveChanges();
}
}
}
采纳答案by Alex Filipovici
You should get a reference to the child and owner objects in the same context. An approach for this would be to get the ids and then pass them as parameters to the AssociateAndSave(int oId, int cId)
method.
您应该在同一上下文中获得对子对象和所有者对象的引用。一种方法是获取 id,然后将它们作为参数传递给AssociateAndSave(int oId, int cId)
方法。
Then, you retrieve the references to the objects in the same contextand you make the attachment.
然后,您检索对同一上下文中对象的引用并进行连接。
private static void Main(string[] args)
{
DeleteAllEntities();
CreateInitialEntities();
int oId = LoadOwnerId();
int cId = LoadChildId();
AssociateAndSave(oId, cId);
}
private static int LoadOwnerId()
{
using (var context = new ModelEntities())
{
return (from o in context.Owners
select o).First().Id;
}
}
private static int LoadChildId()
{
using (var context = new ModelEntities())
{
return (from c in context.Children
select c).First().Id;
}
}
private static void AssociateAndSave(int oId, int cId)
{
using (var context = new ModelEntities())
{
var owner = (from o in context.Owners
select o).FirstOrDefault(o => o.ID == oId);
var child = (from o in context.Children
select o).FirstOrDefault(c => c.ID == cId);
owner.Children.Add(child);
context.Attach(owner);
context.SaveChanges();
}
}
回答by Freeman
You cannot delete objects from one context, with an instance of another context, because each context tracks its objects separately.
您不能从一个上下文中删除对象,并使用另一个上下文的实例,因为每个上下文分别跟踪其对象。
One ideea would be to provide each of your methods a parameter of your context type so your operations are made within the same context.
一个想法是为您的每个方法提供一个您的上下文类型的参数,以便您的操作在相同的上下文中进行。
EX:
前任:
private static void CrudOperationExample(DBContext contextInstane)
{
//perform crud operations.
}
I you want to do it more nicely, i suggest you look for dependency injection, as it is very much helpful in ORM's .
我想做得更好,我建议你寻找依赖注入,因为它在 ORM 的 .