简体   繁体   English

无法定义两个对象之间的关系,因为它们附加到不同的 ObjectContext 对象

[英]The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects

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.我已经多次阅读您应该创建 EF4 上下文,使用它,然后处理它。 Throughout my application, I'm loading entities here and there using different context objects, and then eventually want to associate the entities together.在我的整个应用程序中,我使用不同的上下文对象在这里和那里加载实体,然后最终希望将这些实体关联在一起。

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.如果我只是错过了一个已经存在的、合适的问题/答案,请把我指向正确的地方。

简单的 EF4 模型图

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();
        }
    }
}

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 context and 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();
    }
}

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 的 .

暂无
暂无

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

相关问题 无法定义两个对象之间的关系,因为它们附加到不同的ObjectContext对象Entity Framework - The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects Entity Framework “无法定义两个对象之间的关系,因为它们被附加到不同的ObjectContext对象。” -错误 - 'The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.' - Error 引发异常:因为两个对象附​​加到不同的ObjectContext对象,所以无法定义它们之间的关系 - Exception thrown: The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects EF4错误:无法定义两个对象之间的关系,因为它们附加到不同的ObjectContext对象 - EF4 error:The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects 实体框架v4 - 无法定义两个对象之间的关系,因为它们附加到不同的ObjectContext对象 - Entity Framework v4 - The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects 无法定义两个对象之间的关系,因为它们已附加到不同的ObjectContext对象 - The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects 实体框架:“无法定义两个对象之间的关系,因为它们附加到不同的 ObjectContext 对象。” - Entity Framework: “The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.” 无法定义关系,因为它们已附加到不同的ObjectContext对象 - Relationship cannot be defined because they are attached to different ObjectContext objects 无法找出哪些两个对象附​​加到不同的ObjectContext对象 - Cannot figure out which two objects are attached to different ObjectContext objects 无法定义两个对象之间的关系-为什么? - The relationship between the two objects cannot be defined - why?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM