简体   繁体   中英

Cannot insert to database using LINQ to SQL

I have button and grid view in my app and whenever I click this button I want add new record to database and display updated table in grid view. But for some reason I cannot add but when I click this button again its says 'System.Data.Linq.DuplicateKeyException' . So it seems that it is added for my grid view is still the same and there is no chagnes in database.

This is my onclick method:

private void button2_Click(object sender, EventArgs e)
        {
            database = new DataClasses1DataContext();
            dataGridView1.DataSource = database.Orders;
            Order order = new Order();
            order.Id = 32;
            order.units = 555;
            database.Orders.InsertOnSubmit(order);
            database.SubmitChanges();

            dataGridView1.DataSource = database.Orders;
        }

If your table Order in the database got the primary Key on ID, you can't add another Order with the same ID. Then change your order.ID !

EDIT : let order.id to null and add auto-increment to your primary-key Maybe the DB won't let you add the Order because he got a value on the Id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM