CodeFirst.ApplyChanges? [英] CodeFirst.ApplyChanges?
问题描述
您好,
对于使用CodeFirst的实体,ApplyChanges的优先/最佳实践方法是什么? 我想轻松地将它添加到我的DbContext中,而不必检查它是否存在。 使用SelfTrackingEntities,有一个简单的扩展方法(ApplyChanges)
,这使得这非常直接。 目前,似乎我必须做一些检查,看看实体是否存在于DbContext中,我想要解决这个问题。 :)
What is the preffered/best practice way to ApplyChanges to an entity with CodeFirst? I want to easily add it to my DbContext without having to check to see if it exists. With SelfTrackingEntities, there was a simple extension method (ApplyChanges) that made this very straight forward. Currently, it appears that I have to do some checking to see if the entity exists within the DbContext and I'm wanting to get around that. :)
谢谢!
Michael
推荐答案
我很接近,但是CTP5中似乎有一个错误:
I am close on this, but there appears to be a bug in CTP5:
考虑以下扩展方法:
public static TEntity ApplyChanges<TEntity>( this DbContext target, TEntity entity ) where TEntity : class
{
var set = target.Set<TEntity>();
var values = target.ResolveKeyValues( entity );
var current = set.Find( values );
if ( current != null )
{
Update( target, entity, current );
}
else
{
target.Add( entity );
}
return entity;
}
这篇关于CodeFirst.ApplyChanges?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!