Search code examples
entity-frameworkentity-framework-4.1ef-code-first

How do I detach objects in Entity Framework Code First?


There is no Detach(object entity) on the DbContext.

Do I have the ability to detach objects on EF code first?


Solution

  • If you want to detach existing object follow @Slauma's advice. If you want to load objects without tracking changes use:

    var data = context.MyEntities.AsNoTracking().Where(...).ToList();
    

    As mentioned in comment this will not completely detach entities. They are still attached and lazy loading works but entities are not tracked. This should be used for example if you want to load entity only to read data and you don't plan to modify them.