无法添加具有已在使用中的键的实体错误 [英] Cannot add an entity with a key that is already in use Error

查看:84
本文介绍了无法添加具有已在使用中的键的实体错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我将Northwind数据库用于linq查询.从datagrid收到的记录
并将其用于在Customer和Order表中插入记录.但是会发生此异常无法使用已使用的键添加实体,并且出现错误"



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"

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();

推荐答案

实体框架跟踪与当前数据上下文相关的所有对象,这就是您要获取的原因错误.

尝试将对象直接添加到客户,并调用它应该有帮助的数据上下文的Save方法.

如果这样做无济于事,请确切地指出出现错误的那一点.
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.


这篇关于无法添加具有已在使用中的键的实体错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆