通用实体框架存储库的更新方法 [英] Update method for generic Entity framework repository
问题描述
我有一个这样的存储库:
I have a repository like that:
public class Repository<T> : IRepository<T> where T : class
{
private readonly IRepositoryContext _repositoryContext;
public Repository(IRepositoryContext repositoryContext)
{
_repositoryContext = repositoryContext;
_objectSet = repositoryContext.GetObjectSet<T>();
}
public virtual void Update(T entity)
{
ObjectSet.AddObject(entity);
_repositoryContext.ObjectContext.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
_repositoryContext.SaveChanges();
}
}
现在实际上适用于实体的所有标量属性,但是与实体 typeOf(T)
的属性相关联的所有其他实体不关心实体状态被修改,EF简单地添加新数据。
Now that actually works for all scalar properties of the entity, but all the other entities that associated with properties of entity typeOf(T)
, don't care that entity state is modified, and EF simply adds new data.
所以,如果你做例如 Repository< Student> .Update()
,你只更改了名字,它会找到正确的学生,并更改他的名字,但它也会改变校园,虽然你已经有一个校园与该学生相关联,它将再次创建与不同的校园标识。
So, if you do for example Repository<Student>.Update()
, and you only changed the name, it will find the right Student and change his name, but it also will change the Campus, although you already have a Campus associated with that student, it will be created again with a different CampusId.
请在这种情况下向我显示正确的更新方式。
Show me please the correct way to do updates in this situation.
推荐答案
遵循通用方法已被转换为您的代码,例如:
What I did when I wanted to follow generic approach was translated to your code something like:
public class Repository<T> : IRepository<T> where T : class
{
...
public virtual void Update(T entity)
{
if (context.ObjectStateManager.GetObjectStateEntry(entity).State == EntityState.Detached)
{
throw new InvalidOperationException(...);
}
_repositoryContext.SaveChanges();
}
}
我的所有代码的工作原理如下:
All my code then worked like:
var attachedEntity = repository.Find(someId);
// Merge all changes into attached entity here
repository.Update(attachedEntity);
=>以通用方式执行此操作会将大量逻辑移动到上层。没有更好的方法来保存大的分离对象图(特别是涉及多对多关系并涉及关系的删除)。
=> Doing this in generic way moves a lot of logic into your upper layer. There is no better way how to save big detached object graphs (especially when many-to-many relations are involved and deleting of relations is involved).
这篇关于通用实体框架存储库的更新方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!