Skip to content

Instantly share code, notes, and snippets.

@wasimf
Created November 10, 2013 14:06
Show Gist options
  • Save wasimf/7398694 to your computer and use it in GitHub Desktop.
Save wasimf/7398694 to your computer and use it in GitHub Desktop.
AttachToOrGet from entity framework context
public static void AttachToOrGet<T>(this ObjectContext context, string entitySetName, ref T entity)
where T : IEntityWithKey
{
ObjectStateEntry entry;
// Track whether we need to perform an attach
bool attach = false;
if (
context.ObjectStateManager.TryGetObjectStateEntry
(
context.CreateEntityKey(entitySetName, entity),
out entry
)
)
{
// Re-attach if necessary
attach = entry.State == EntityState.Detached;
// Get the discovered entity to the ref
entity = (T)entry.Entity;
}
else
{
// Attach for the first time
attach = true;
}
if (attach)
context.AttachTo(entitySetName, entity);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment