我如何解决此错误 [英] How I Solve This Error

查看:203
本文介绍了我如何解决此错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我使用linq将数据插入到两个表中具有一对多的关系
当第二次插入时,此消息出现??

Hi everybody i''m using linq to insert data into two tables have relation one to many
when insert second time this message appear ??

Violation of PRIMARY KEY constraint 'PK__customer__26A1118D08EA5793'. Cannot insert duplicate key in object 'dbo.customeraddress'.
The statement has been terminated.





我的代码:





my code :

DbDataContext db = new DbDataContext();

            customer cust = new customer();
            
            cust.firstname = textBox1.Text;
            cust.Lastname = textBox2.Text;
        
            db.customers.InsertOnSubmit(cust);
            db.SubmitChanges();

            customeraddress custaddress = new customeraddress();
           
                custaddress.states = textBox3.Text;
                custaddress.address1 = textBox4.Text;

                cust.customeraddresses.Add(custaddress);
            db.SubmitChanges();

推荐答案

该错误消息非常清楚,您正在尝试插入包含与该数据完全相同的数据的行在您表中定义为主键的列的另一行中已经存在.

主键的目的是防止重复,因此避免出现错误消息.

为了查看主键,请打开Sql Server Management Studio,导航到您的数据库和表,右键单击该表并选择设计".在那里,您应该在列前面看到一个为主键的键图标.

另一种选择是运行查询以获取主键信息.为此,您可以尝试以下操作:
The error message is quite clear, you''re trying to insert a row that contains the exact same data that already exists in another row in your table in the column(s) you have defined as primary key.

The purpose of the primary key is to prevent duplicates, hence the error message.

In order to see the primary key, open Sql Server Management Studio, navigate to your database and table, right click the table and select Design. There you should see a key icon in front of the column(s) that is primary key.

Another option is to run a query to get the primary key info. For that you can try the following:
SELECT a.TABLE_CATALOG,
       a.TABLE_NAME,
       a.COLUMN_NAME,
       a.ORDINAL_POSITION
FROM  INFORMATION_SCHEMA.KEY_COLUMN_USAGE a
WHERE a.CONSTRAINT_NAME = 'PK__customer__26A1118D08EA5793'
ORDER BY a.ORDINAL_POSITION


这篇关于我如何解决此错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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