Entities - how detach from context EF5 RRS feed

  • Question

  • User-253199000 posted


    I have 1:n relationship for Category, Subcategory and Products in my Entity Model.

    In order so solve this problem: http://forums.asp.net/t/2050254.aspx?LINQ+set+where+condition+for+included+entity

    I loaded each table into a List<T>:

    List<Category> c = (from q in context.Categories select q).ToList()
    List<Subcategory> s = (from q in context.Subcategories select q).ToList()
    List<Product> p = (from q in context.Products select q).ToList()

    and then tried to manipulate those (delete and add entities). Unfortunately I recognized that every Add() and Clear() will cause a query to the database whether the foreign key constraint is valid. This is time wasting. How can I detach my data from the context completely? I'm using EF5 - so there is no Detach method in the object context. Using context.Categories.AsNoTracking() did not work either.

    Thanx for help,


    Sunday, May 10, 2015 9:44 AM


  • User-253199000 posted

    Hi Dillion,

    Thanx for your help. But the the mentioned Detach-methods do not seem to exist in EF5.

    Instead I finally found out this way to solve the issue: after loading all into Lists, you have to change the EntityState of each Entity:

    p.ForEach(p => context.Entry(p).State = EntityState.Detached);
    s.ForEach(s => context.Entry(s).State = EntityState.Detached);
    c.ForEach(c => context.Entry(c).State = EntityState.Detached);


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 13, 2015 5:08 AM

All replies