检索导航属性会更改上下文

时间:2014-06-02 04:56:41

标签: entity-framework

我有一个带有以下代码的存储库类来更新已更改的实体。 但是我收到了错误

"The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects."

但是我无法看到上下文已经改变,因为它是我的存储库的属性。

我在存储库中

protected  void InnerUpdate(params T[] items)
    {
        DbSet<T> dbSet = ((DbContext)this.context).Set<T>();
        foreach (T item in items)
        {
                    object id1 = item.GetProperty("Id");
                    T originalEntity = dbSet.Find(id1);
                    ((DbContext)this.context).Entry(originalEntity).CurrentValues.SetValues(item);

                    var navProps = GetNavigationProperties(originalEntity);
                    foreach (var navProp in navProps)
                    {
                        //Set originalEntity prop value to modifiedEntity value
                        navProp.SetValue(originalEntity, navProp.GetValue(item));

                    }
            }
        }

        this.context.SaveChanges();  // Error occurs here
    }


    public List<PropertyInfo> GetNavigationProperties(T entity )
    {
        var t = entity.GetType();
        ObjectContext objectContex = ((IObjectContextAdapter)((DbContext)this.context)).ObjectContext;

        var elementType = objectContex.CreateObjectSet<T>().EntitySet.ElementType;


        var properties = new List<PropertyInfo>();
        var entityType = entity.GetType();
        foreach (var navigationProperty in elementType.NavigationProperties)
        {
            properties.Add(entityType.GetProperty(navigationProperty.Name));
        }
        return properties;
    }

我想知道问题是否是由于调用CreateObjectSet引起的?有没有不同的方法来做到这一点? 我正在使用EF6.1

1 个答案:

答案 0 :(得分:2)

我按如下方式更改了代码并使其正常工作

                    var navProps = GetNavigationProperties(originalEntity);
                    foreach (var navProp in navProps)
                    {
                        //Set originalEntity prop value to modifiedEntity value
                        var newval = (LoggedEntity) navProp.GetValue(item);
                        object entity = null;
                        if (newval != null)
                        {
                            var tp = navProp.PropertyType;
                            var entities = ((DbContext)this.context).Set(tp);
                            entity = entities.Find(newval.Id);
                        }
                        navProp.SetValue(originalEntity, entity);
                    }