Monday, April 25, 2011

Detaching entity along with referenced entities.

Ok, I am planning to develop a project using Entity Framework. While i was trying to do some R&D before i kick off implementing it, I found this problem, hope some of you people help me find a solution to it.

I have a entity named 'Person' referenced with 'Members' entity with one to many (1:N) relationship. The task would be to query Person entity along with its corresponding Members collection and pass it to the presentation layer to view, modify or delete over it and then the modified entity object will be passed back to the Model layer to attach the entity to the context and save it to the DB.

As far as I Detach/Attach w.r.t. a single entity like 'Person' and save it to the DB every thing works absolutely fine. But, when i try to query an entity (Person) with its referenced entity (Member) and detach so that i can send it to the presentation layer. I find that I get only Person entity collection and the reference Member entity collection is totally removed after detaching it from the context.

Here I am pasting my code snippet for reference:

using (GOLProfessionalEntities context = new GOLProfessionalEntities())
{
     ObjectQuery<Person> query =
        context.Person.Include("Members");

     var person = query.First();
     context.Detach(person);

     return person;
}

I would be really delighted if some one comes out with a solution to this.

Thanks in advance. -ssak32

From stackoverflow
  • I believe you need to detach each Member also:

    using (GOLProfessionalEntities context = new GOLProfessionalEntities()) { ObjectQuery query = context.Person.Include("Members");

     var person = query.First();
    
    
     while (person.Member.Count > 0)
     {
         context.Detach(person.Member.First());
     }
    
    
     context.Detach(person);
    
     return person;
    

    }

    I hope that works.

  • You could set MergeOption on ObjectQuery to NoTracking. This way Person will not be attached to the ObjectContext in the first place.

                using (GOLProfessionalEntities context = new GOLProfessionalEntities())
                {
                    ObjectQuery<Person> query =
                       context.Person.Include("Members");
                    query.MergeOption = MergeOption.NoTracking;// <--
    
                    var person = query.First();
    
                    return person;
                }
    

    I'm so late with the answer by it might help someone.

0 comments:

Post a Comment