实体框架 - 异常添加现有对象

时间:2013-10-15 18:49:36

标签: entity-framework entity-framework-5

当我使用add()向db输入实体时,我得到以下SqlException(对象已经存在)

Violation of PRIMARY KEY constraint '....'. 
Cannot insert duplicate key in object 'PROJ.DesignProjects'. 
The duplicate key value is ... The statement has been terminated."} 
System.Exception {System.Data.SqlClient.SqlException}

我然后修复它以在添加之前运行删除并且我得到

{"An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."}

我怎么能突然出现?

1 个答案:

答案 0 :(得分:0)

尝试使用AddOrUpdate()方法:

yourContext.yourDbSet.AddOrUpdate(yourObject);

修改:进一步阅读http://msdn.microsoft.com/en-us/library/hh846520(v=vs.103).aspx