2012-01-16 54 views
3

对于下面的代码的实体,收到消息:不能附加已经存在

不能附加已经存在的实体。

C#代码:

var con = (from c in cmsContentTable where c.ContentName == contentId select c).FirstOrDefault(); 
cmsContentTable.Attach(con); 
con.ContentData = "New Value"; 
cmsContentTable.Context.SubmitChanges(); 

为什么给这个错误 - 这是因为骗子参考已经取得 时

var con = (from c in cmsContentTable where c.ContentName == contentId select c).FirstOrDefault(); 

做?

+1

如何为您的ORM框架添加标签? – CodesInChaos

+0

可能重复[无法附加已存在的实体](http://stackoverflow.com/questions/2605657/cannot-attach-an-entity-that-already-exists) –

回答

4

既然你已经从表中获取的项目:

var con = (from c in cmsContentTable where c.ContentName == contentId select c).FirstOrDefault(); 

的上下文已经“连接”的对象。只要您从表格中拉出已存在的对象,情况就是如此。

如果您删除行:

cmsContentTable.Attach(con); 

你应该罚款。

更有用的消息是“无法附加到已经附加到上下文的实体”,因为这是实际发生的情况。