新添加对象的实体对象而不是动态代理 Entity framework

Entity object for newly added objects instead of dynamic proxy Entity framework

我有一个存储库,其中包含添加和搜索方法

   public virtual void Add(T obj)
    {
        _table.Attach(obj);
        _table.Add(obj);
    }


     public virtual IEnumerable<T> Search(Expression<Func<T, bool>> predicate)
    {
        return _db.Set<T>().Where(predicate);
    }

然后在我的控制器上使用添加方法添加新的客户注释对象并保存更改后我使用搜索根据客户 ID 检索注释,我得到如下图所示的列表,新添加的对象是键入 poco class 并且所有虚拟导航属性都未加载我通过使用 include 做了一个解决方法,是否解释了为什么 EF 这样做

Quick watch List for retrieved list from search method

EF 仅为它创建的实体实例创建代理 - 在具体化查询时隐式或在使用 DbSet.Create 方法时显式。任何接收用户提供的对象实例(如 AddRemoveAttachEntry 等)的方法都不会修改(用代理包装)传递的对象。

为什么?因为这样做会使许多方法抛出 "The instance of entity type X cannot be tracked because another instance of this type with the same key is already being tracked",因为 EF 使用 reference equality 来跟踪实体实例。

如果您附加、添加等普通(非代理)对象实例,它们将在上下文的生命周期内保持这种状态或直到明确分离。