Click here to Skip to main content
15,906,558 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:


hi

i use Northwind data base for linq query. received record from datagrid
and using it to inserting record in Customer and Order tables.but ocure this exception "Cannot add an entity with a key that is already in use Error"

C#
var Nwind_dc = new DataClasses1DataContext();
          
            foreach (var Cust in GridTable)
            {
                var customer = new Customer
                {
                    CustomerID = Cust.CustomerID,
                    CompanyName = Cust.CompanyName,
                    ContactTitle = Cust.ContactTitle


                };

                var order = new Order { OrderDate = Cust.OrderDate, EmployeeID = Cust.EmployeeID };
               
                customer.Orders.Add(order);
                Nwind_dc.Customers.InsertOnSubmit(customer);
                
             
            }
            Nwind_dc.SubmitChanges();
Posted
Updated 10-Apr-12 0:39am
v2

1 solution

the entity framework tracks all the objects that are related to the current data context that's why you are getting the error.

try Adding object to the customers directly and calling the Save method of the data context it should help.

If it does not help please post exactly which point you are getting the error.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900