Skip to content

Instantly share code, notes, and snippets.

@ismyrnow
Created October 22, 2011 23:17
Show Gist options
  • Save ismyrnow/1306612 to your computer and use it in GitHub Desktop.
Save ismyrnow/1306612 to your computer and use it in GitHub Desktop.
AtachOrUpdate extension method for Entity Framework
public static void AttachOrUpdate<T>(this ObjectSet<T> set, ref T entity) where T : class
{
ObjectContext context = set.Context;
string entitySetName = set.EntitySet.Name;
ObjectStateEntry entry;
bool isDetached = true;
if (context.ObjectStateManager.TryGetObjectStateEntry(
context.CreateEntityKey(entitySetName, entity),
out entry))
{
// Check if it's detached
isDetached = entry.State == EntityState.Detached;
// Update the context entry
entry.ApplyCurrentValues(entity);
// Set the entity to the discovered entry
entity = (T)entry.Entity;
}
// If no object state entry is found, we must be detached
// If it's detached, attach it
if (isDetached)
{
set.Attach(entity);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment