I used EF 6.2.0 DB first, SQL Server 2017
I created a table to test this
create table Person
(
ID int primary key,
Name varchar(50)
)
And I created a form to insert, this is button click event:
private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
Person p = new Person();
p.id = Convert.ToInt32(txbID.Text);
p.name = txbName.Text;
try
{
db.People.Add(p);
db.SaveChanges();
}
catch (Exception ex)
{
Console.WriteLine("###Ex:" + ex.ToString());
MessageBox.Show(ex.ToString());
}
}
First, I insert a person with ID = 1
.
Then, I insert another person with ID = 1
and it caused this exception:
System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'PK__Person__3213E83F397C4503'. Cannot insert duplicate key in object 'dbo.Person'. The duplicate key value is (1).
Finally, I insert a person with ID = 2
and it still show the same exception:
System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'PK__Person__3213E83F397C4503'. Cannot insert duplicate key in object 'dbo.Person'. The duplicate key value is (1).
After the first exception, insert any ID will cause the same exception The duplicate key value is (1)
. I think it's a bug.
No, it's not a bug - I suspect you haven't really understood how the
DbContext
works.When you try to insert the second person with
ID = 1
which will obviously create the error, that object (that causes this error) is now part of theDbContext
(of thedb.People
collection).If you add another person, with
ID = 2
, your "problematic" second person withID=1
is still part of theDbContext
(db.Person
) - unless you've specifically cleaned up (removed that troublesome person, or created a newDbContext
altogether).So after adding the person with
ID = 2
, yourDbContext
now has a Person with ID=1 and another one with ID=2 to be saved when calling.SaveChanges()
- and that will OF COURSE again fail with the same error - it's the same problem as before......One way to solve this would be to explicitly create the
DbContext
inside yourbtnSubmit_Click
method: