❔ EF Core duplicating many-to-many?
After saving, the references are duplicated!
var entityShowcase = new Models.Showcase
{
AuthorId = showcase.AuthorId,
Description = showcase.Description,
Title = showcase.Description,
Summary = showcase.Summary,
ImageSource = showcase.ImageSource,
MajorVersion = showcase.MajorVersion,
MinorVersion = showcase.MinorVersion,
PatchVersion = showcase.PatchVersion,
};
foreach (var feature in showcase.Features)
{
var dbFeatures = _context.Feature.FirstOrDefault(x => x.Value == feature);
if (dbFeatures is not null)
{
entityShowcase.Features.Add(dbFeatures);
continue;
}
entityShowcase.Features.Add(new Feature { Value = feature });
}
// after the loop above, enitityShowcase features is 2 (as it should be)
var entityEntry = await _context.AddAsync(entityShowcase, cancellationToken);
// after adding, it's actually 4...
await _context.SaveChangesAsync(cancellationToken);
return entityEntry.Entity.Id; var entityShowcase = new Models.Showcase
{
AuthorId = showcase.AuthorId,
Description = showcase.Description,
Title = showcase.Description,
Summary = showcase.Summary,
ImageSource = showcase.ImageSource,
MajorVersion = showcase.MajorVersion,
MinorVersion = showcase.MinorVersion,
PatchVersion = showcase.PatchVersion,
};
foreach (var feature in showcase.Features)
{
var dbFeatures = _context.Feature.FirstOrDefault(x => x.Value == feature);
if (dbFeatures is not null)
{
entityShowcase.Features.Add(dbFeatures);
continue;
}
entityShowcase.Features.Add(new Feature { Value = feature });
}
// after the loop above, enitityShowcase features is 2 (as it should be)
var entityEntry = await _context.AddAsync(entityShowcase, cancellationToken);
// after adding, it's actually 4...
await _context.SaveChangesAsync(cancellationToken);
return entityEntry.Entity.Id;