Returning the DbContext.Detach () method using the extension method (EF5)

There is no Detach(object entity) in DbContext in Entity Framework 5.

To detach an object, you now need to change the state. Maybe something is missing for me, but it seems less clear and understandable than using the Detach method:

 context.Entry(myEntity).State = EntityState.Detached; 

I am tempted to just create an extension method to return the Detach method:

 public static void Detach(this MyEntities context, object entity) { context.Entry(entity).State = EntityState.Detached; } 

What is the reason Microsoft removed the DbContext.Detach () method in EF 5?

+8
c # entity-framework-5 entity-framework
source share
2 answers

Removing the Detach method from the API ( DbContext ) has some logic, since Detach does not work on the object graph, but only separates the only object that you pass to the method. This is different from all other methods that change the state of an object:

  • Attach attaches the supplied object, including all related objects in the object graph of the navigation properties.
  • Add adds the supplied object, including all related objects to the context.
  • Remove removes the provided object, including related objects that were configured using cascading deletion

On the other hand, manual installation of Modified , Added or Deleted manually always affects only the provided object, and not related objects. This also applies to calling the Detach ObjectContext method. Rather, it is connected with detaching an object only by setting the state to Detached in accordance with the behavior of other state changes, because, as in the case of any other state, it only affects the provided object without associated objects.

DbContext is among other features designed to simplify working with the Entity Framework. The old Detach method was more confusing, and its behavior was unlike the expectations of many developers. ( Here and here are two links about this confusion and the difficulties associated with detaching an object.) In my opinion, this was not the wrong step to remove it from the DbContext API.

Well, you can always write your own extension method, just like you, or access the underlying ObjectContext through an adapter if you really want to have a Detach method.

+16
source share

I have no idea why there is no Detach() method, but the DbSet class provides the AsNoTracking() method to retrieve objects that are disconnected from DbContext .

Here is a sample code from here

 using (var context = new UnicornsContext()) { // Query for all unicorns without tracking them var unicorns1 = context.Unicorns.AsNoTracking(); // Query for some unitcorns without tracking them var unicorns2 = context.Unicorns .Where(u => u.Name.EndsWith("ky")) .AsNoTracking() .ToList(); } 
+5
source share

All Articles