将EF 4添加/附加方法转换为EF 6

尖刺

对于运行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,并能正常工作?

我已更改CreateObjectSetSet,但是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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章