Primary key violation

I started with C # and I wanted to create my own DB.

I have two models

public class AModel { public Guid ID { get; private set; } public string Name { get; set; } public int Count { get; set; } public AModel() { this.ID = Guid.NewGuid(); } } public class BModel { public Guid ID { get; private set; } public string Name { get; set; } public AModel Model { get; set; } public BModel() { this.ID = Guid.NewGuid(); } } 

When I try to save the BModel to DB, I get this error:

Violation of the PRIMARY KEY constraint 'PK_dbo.AModels'. Cannot insert duplicate key in object 'dbo.AModels'. Duplicate key value (48ee1711-8da4-46c1-a714-19e985211fed). The application was terminated.

I thought it would be solved by this.

 modelBuilder.Entity<BModel>().HasRequired(t => t.Model).WithMany(); 

but it seems like I'm completely lost. Can someone help me with this simple example?

+6
source share
1 answer

Your comment shows important information. When you add this AModel from your combobox to your BModel, it will be disconnected from your DbContext. When you add it to your model, the Entity Framework will think that you have a new object.

Since you have identifiers configured as DatabaseGenerationOptions.None, it will use the primary key that you provide to yourself. In your case, this is a PC of a separate object. Thus, when EF tries to insert this record, it will throw the above exception because an object with this key is already present.

There are several ways to solve this problem:

  • Get existing object

This object will be attached to your context after retrieval, which allows you to use it. This means an additional search: first, to get them in combobox, and then use the Id from the object in combobox to get it again from the database.

Usage example:

 AModel Get(AModel detachedModel) { using(var context = new MyContext()) { return context.AModels.Single(x => x.ID == detachedModel.ID); } } 
  • Attach an existing model

This should simply make Entity-Framework know that the object already exists in the database.

 using(var context = new MyContext()) { context.AModels.Attach(detachedModel); } 

Other connection methods - setting the state to "No change"

 context.Entry(detachedModel).State = EntityState.Unchanged; 

or Modified (in case you also changed the values)

 context.Entry(detachedModel).State = EntityState.Modified; 
+11
source

Source: https://habr.com/ru/post/985435/


All Articles