Created
January 8, 2014 16:03
-
-
Save mhinze/8319128 to your computer and use it in GitHub Desktop.
A useful little EF extension method
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
using System; | |
using System.Data.Entity; | |
public static class EntityFrameworkExtensions | |
{ | |
/// <summary> | |
/// Given an id, creates a reference to an existing (persisted) *unchanged* entity | |
/// </summary> | |
/// <typeparam name="TEntity">Entity CLR type</typeparam> | |
/// <param name="db">DbContext</param> | |
/// <param name="id">Entity Id</param> | |
/// <returns></returns> | |
public static TEntity GetEntityReference<TEntity>(this DbContext db, Guid id) where TEntity : Entity, new() | |
{ | |
foreach (var entity in db.ChangeTracker.Entries<TEntity>()) | |
{ | |
// the entity is already being tracked | |
if (entity.Entity.Id == id) | |
{ | |
return entity.Entity; | |
} | |
} | |
var temp = db.Entry(new TEntity { Id = id }); | |
temp.State = EntityState.Unchanged; | |
return temp.Entity; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usually use something like this as an entity base class... https://gist.github.com/mhinze/1315423