Created
November 10, 2013 14:06
-
-
Save wasimf/7398694 to your computer and use it in GitHub Desktop.
AttachToOrGet from entity framework context
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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