对于运行EF 4的应用程序,我在存储库基类中具有以下方法:
protected void Add<T>(T source, MyEntities context, bool isNew, EntityState state) where T : class
{
if (isNew)
{
context.CreateObjectSet<T>().AddObject(source);
}
else
{
if (state == EntityState.Detached)
{
context.CreateObjectSet<T>().Attach(source);
context.ObjectStateManager.ChangeObjectState(source, EntityState.Modified);
}
}
}
给定运行它的版本,该方法可以很好地工作,但是我正在从头开始使用EF 6的新项目。
如何更新上述功能以适合EF 6,并能正常工作?
我已更改CreateObjectSet
为Set
,但是AddObject
未知。这样做似乎对附加操作有效,但是我不知道如何替换该ObjectStateManager
内容。
IDbSet<T>
包含一个Entry<T>()
返回DbEntityEntry<T>
具有读取/写入State
属性的的方法。
您的代码可以转换为以下代码:
protected void Add<T>(T source, MyEntities context, bool isNew)
where T : class
{
IDbSet<T> set = context.Set<T>();
if (isNew)
{
set.Add(source);
}
else
{
DbEntityEntry<T> entry = set.Entry(source);
if (entry.State == EntityState.Detached)
{
set.Attach(source);
entry.State = EntityState.Modified;
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句