关于 Table<TEntity>.Attach(),据说它的作用就是可以在不同的DataContext当中附加数据,让被附加的数据(实体)即使在外部(DataContext上下文之外)修改也可以让别的DataContext中的对应数据得以更新。

假设我已经有一个Category的实体类与对应的数据库表。
相关类代码如下:

 1Debug 对 Linq to Sql 有什么影响吗?    public class DataAccess
 2    }


Debug 对 Linq to Sql 有什么影响吗?    public class DLContext:DataContext
    }

 1Debug 对 Linq to Sql 有什么影响吗?        static void Main(string[] args)
 2        }


为什么当我不设断点的时候,会出现Exception:
"An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext.  This is not supported."
当我在13行  DataAccess.Attach(category);处设了一个断点,而且用鼠标放在category上查看了一下属性值,继续运行,它就不会出错,一切正常了!!!!

是什么原因啊?????

---------------------------------------------------------------------

经大侠指引,终天知道原来因为Category 表中有一个外键,对于实体类Category, 有一个字段:

private EntityRef<Parent> _Parent;

必须在调用 Attach()方法之前,先令
_Parent=default(EntityRef<Parent> );

综上所述,为了方便使用,我在Category类中加了一个Detach()方法:

Debug 对 Linq to Sql 有什么影响吗?public void Detach()
}

必须在调用 Table<TEntity>.Attach()方法之前,先调用category.Detach()方法。



 

相关文章:

  • 2021-12-26
  • 2021-12-19
  • 2021-10-22
  • 2021-10-22
  • 2022-12-23
  • 2021-08-22
  • 2021-09-30
猜你喜欢
  • 2021-07-22
  • 2021-11-15
  • 2021-10-18
  • 2021-11-07
  • 2021-11-22
  • 2022-12-23
  • 2021-06-08
相关资源
相似解决方案