I get the following errors when I try to insert a movie with a list of unique genres.
System.InvalidOperationException: The instance of entity type ‘Genre’ cannot be tracked because another instance with the same key value for {‘Id’} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using ‘DbContextOptionsBuilder.EnableSensitiveDataLogging’ to see the conflicting key values.
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap1.ThrowIdentityConflict(InternalEntityEntry entry) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap
1.Add(TKey key, InternalEntityEntry entry, Boolean updateDuplicate)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap1.Add(TKey key, InternalEntityEntry entry) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap
1.Add(InternalEntityEntry entry)
Question
What is the correct way to insert it?
Here are my entities
public class Movie
{
public int Id { get; set; }
public string Title { get; set; } = null!;
public ICollection<Genre> Genres { get; set; } = [];
}
[Index(nameof(Name), IsUnique = true)]
public class Genre
{
public int Id { get; set; }
public string Name { get; set; } = null!;
public ICollection<Movie> Movies { get; set; } = [];
}
public class AppDbContext(DbContextOptions<AppDbContext> o) : DbContext(o)
{
public DbSet<Movie> Movies { get; set; }
public DbSet<Genre> Genres { get; set; }
}
And my web api:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlite("DataSource=Movie.db"));
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
using IServiceScope scope = DevelopmentSeeder(app);
}
app.MapPost("movies", async Task<Ok> (AppDbContext db) =>
{
Genre[] genres =
[
new Genre{Name="comedy"},
new Genre{Name="action"},
new Genre{Name="drama"},
new Genre{Name="horror"},
];
foreach (var genre in genres)
{
var existing = await db.Genres.FirstOrDefaultAsync(g => g.Name == genre.Name);
if (existing is null)
{
db.Genres.Add(genre);
}
else
{
genre.Id = existing.Id;
}
}
var movie = new Movie
{
Title = "I don't know",
Genres = genres
};
db.Movies.Add(movie);
await db.SaveChangesAsync();
return TypedResults.Ok();
});
app.Run();
static IServiceScope DevelopmentSeeder(WebApplication app)
{
var scope = app.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
db.Database.EnsureDeleted();
db.Database.EnsureCreated();
Genre[] genres =
[
new Genre{Name="comedy"},
new Genre{Name="action"},
];
db.Genres.AddRange(genres);
Movie movie = new Movie
{
Title = "Kungfu Hustle",
Genres = genres
};
db.Movies.Add(movie);
db.SaveChanges();
return scope;
}