Skip to content

Instantly share code, notes, and snippets.

@mhinze
Created January 8, 2014 16:03
Show Gist options
  • Save mhinze/8319128 to your computer and use it in GitHub Desktop.
Save mhinze/8319128 to your computer and use it in GitHub Desktop.
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;
}
}
@mhinze
Copy link
Author

mhinze commented Jan 8, 2014

Usually use something like this as an entity base class... https://gist.github.com/mhinze/1315423

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