Entity Framework 4, Self Tracking Entities T4 Template, ApplyChanges() extension method
I am using EF4 and the built in self-tracking entities template to generate my entites from my model. I also modifeid the T4 template so that all of the references to "ObjectContext" were changed to "IObjectContext", and I applied an interface to the auto generated context (all this was for testing and mocking purposes).
//my interface
public inte开发者_高级运维rface IDatabaseEntities
{
IObjectSet<Customer> Customers {get;}
int SaveChanges();
}
//self tracking entity auto gen code, with my mods
public partial class DatabaseEntities : ObjectContenxt, IDatabaseEntities
{
//auto gen stuff here
public IObjectSet<Customer> Customers
//more auto gen stuff
}
In the T4 template they generate an extension method ApplyChanges() which only works on objects with type of "ObjectSet". So I cannot call "_context.Customers.ApplyChanges(customer);" because i am working with types of "IObjectSet". I really need to call this method in order to update a detached entity!!! So now I cannot figure out how to update my entities since I am not working with the concrete ObjectSet class.
How about an extension method like the following:
public static class EntityFrameworkExtensions
{
public static void ApplyChanges<TEntity>(this IObjectSet<TEntity> objectSet, TEntity entity)
where TEntity : class
{
if (objectSet is ObjectSet<TEntity>)
{
((ObjectSet<TEntity>)objectSet).ApplyChanges(entity);
}
}
}
精彩评论