开发者

Cannot insert new Employee entity using InsertOnSubmit()

开发者 https://www.devze.com 2023-03-17 17:54 出处:网络
I\'m facing this 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. when I try to insert a new e

I'm facing this 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. when I try to insert a new entity into my Employees table (the master one).

There is a relationship between the master Employees table and the details Orders table, and I'm sure that the relationship between these two tables (and specifically Employee.Orders EntitySet) is the cause of the problem since when I removed the relationship, it returns back to insert into Employees table with no problems.

When I searched for the problem, there was this blog post which I tried to implement but my case is a different than the one in the blog post in these items:

  • He faces the exception when tries to update (while I try to insert).
  • The tables architecture is different.

how can I solve this problem?

Here's the insertion code:

Employee emp = new Employee();
em开发者_StackOverflow中文版p.Name = empName;    // empName is a local variable

// What should I default emp.Orders to?

dc.Employees.InsertOnSubmit(emp);
dc.SubmitChanges();

P.S: My DataContext is defined on class-level in my repository and the exception is being thrown when I call dc.SubmitChanges();. and I didn't Attach any object why does it say that?


Here is an article explaining what you need to do using the Attach and Detach methods: http://www.codeproject.com/KB/linq/linq-to-sql-detach.aspx


I am guessing it is trying to save something else besides just the employee object or you aren't showing us the full code in your repository. When you instantiate your DataContext object (dc) try setting DeferredLoadingEnabled = false, and ObjectTrackingEnabled = false and see if it works. If it does, try watching the SQL code in SQL Server Profiler and see if it is modifying other objects that may have came from a different context like the message says.

var dc = new MyDataContext() 
{ 
    DeferredLoadingEnabled = false, 
    ObjectTrackingEnabled = false 
}; 


My bet is on the primary key.

  • Are you sure the primary key is also set on auto increment?
  • Did you try changing the name, does it work then?
  • What happens if you remove all rows from your DB? can you insert one then?
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号