将 EF 4 add/attach 方法转换为 EF 6
Convert EF 4 add/attach method to EF 6
对于应用程序 运行 EF 4,我在存储库库中有此方法 class:
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>()
方法,其中 return 一个 DbEntityEntry<T>
有一个 read/write 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;
}
}
}
对于应用程序 运行 EF 4,我在存储库库中有此方法 class:
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>()
方法,其中 return 一个 DbEntityEntry<T>
有一个 read/write 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;
}
}
}