Title: Violation of PRIMARY KEY constraint in Entity Framework Core
Tags: c#;entity-framework;blazor-server-side;.net-5;ef-core-5.0
Question: I have a .NET5 Blazor Server application using EFCore5.
I have two entities that have a many-to-many relationship with each other.
Let's call them 'Books' and 'Tags'.
EFCore provides the BookTag join table.
On my page, I have a form that is populated with the book details and has a multi select box for the tags.
I include the tags when I get the book:
```context.Books.Include(x=&gt;x.Tags);```
In debug mode, I see the Book item has several tags. But when I update some details of the book and save the form, calling ```context.Books.Update(book);``` I get an error because of duplicate keys in the BookTag join table.
It seems EFCore tries to insert entries in that table, but it should do a merge or insert/update.
I've read numerous articles about the many-to-many but all of them just show how to retrieve data. I can't find an example of how to update.
Edit:
I'm using the GenericRepository as explained by @carl-franklin in his excellent BlazorTrain series.
Edit2:
Here is some relevant code, I'm now not using the GenericRepo:
Startup.cs
```services.AddDbContextFactory<ApplicationDbContext&gt;(options =&gt; options.UseSqlServer(Configuration.GetConnectionString(&quot;DbConnection&quot;)));```
ApplicationDbContext.cs has only the ```DbSet```s.
Book.cs
```[Key] 
public string Code { get; set; }
public string Name { get; set; } = &quot;&quot;;
public virtual ICollection<Tag&gt; TagCollection { get; set; }
```
Tag.cs
```[Key] 
public string Code { get; set; }
public string Name { get; set; } = &quot;&quot;;
public virtual ICollection<Book&gt; BookCollection { get; set; }
```
Book.razor.cs
```[Inject] private IDbContextFactory<ApplicationDbContext&gt; contextFactory { get; set; }
private ApplicationDbContext context { get; set; }
protected IEnumerable<Book&gt; BookList;

protected override async Task OnInitializedAsync()
{
    context = contextFactory.CreateDbContext();
    context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
    
    BookList = await context.Books.Include(x =&gt; x.TagCollection).ToListAsync();
}

private async Task UpdateBook(Book book)
{
    // Called after submitting form
    context.Books.Update(book);
    await context.SaveChangesAsync();
}
```
Even if I don't change anything, just update I get the duplicate error:
```Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---&gt; Microsoft.Data.SqlClient.SqlException (0x80131904): Violation of PRIMARY KEY constraint 'PK_BookTag'. Cannot insert duplicate key in object 'dbo.BookTag'```
In UpdateBook() I see the book has tags, as expected. It looks like EFCore is inserting them in the join table without checking if they already exist.

Comment: Show us your code.

Comment: `Violation of PRIMARY KEY constraint 'PK_BookTag'. Cannot insert duplicate key in object 'dbo.BookTag'` -- Kinda says it all.  Not sure why you're turning off change tracking; that's what makes all this work.  `Update` does not mean `Upsert` or `Merge`.

Comment: When you initially read data from database, add `.AsNoTracking()`.

Comment: Thanks Ergis. I'm already doing that. In fact I'm doing it on the context level: `context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;`

Comment: Thanks @RobertHarvey I've updated my post and added relevant code.

Comment: Change tracking was turned off in the GenericRepo I got from BlazorTrain. When in my extracted code I don't turn it off my problems disappear and I can add the tags without errors. As expected. @RobertHarvey If you turn your comment into an answer I'll accept it.

Here is the accepted answer: Change tracking must be turned on for this to work.  Otherwise, you have to track the changes yourself; Entity Framework thinks you're adding a new record, but the key is the same as an existing record, which is why you're getting the error.



{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 6, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2021:00:02/24/21', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<c#><entity-framework><blazor-server-side><.net-5><ef-core-5.0>', 'Title': 'Violation of PRIMARY KEY constraint in Entity Framework Core', 'ViewCount': 1018, 'id': 66353402, 'user_AboutMe': '<p>Release manager, configuration manager</p>\n\n<p>and forum moderator of MapWindow GIS.</p>\n\n<p><a href="http://www.mapwindow.org" rel="nofollow noreferrer">http://www.mapwindow.org</a></p>\n\n<p>Owner of MapWindow.nl - Support for</p>\n\n<p>Dutch speaking users.</p>\n\n<p><a href="http://www.mapwindow.nl" rel="nofollow noreferrer">http://www.mapwindow.nl</a></p>\n', 'user_AccountId': 512938.0, 'user_DisplayName': 'Paul Meems', 'user_Reputation': 2578.0, 'user_Views': 382.0, 'user_id': 1253335.0}}