Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A useful little EF extension method
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;
Copy link

mhinze commented Jan 8, 2014

Usually use something like this as an entity base class...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment