C
C#2y ago
Bread

❔ 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;
2 Replies
Bread
Bread2y ago
Any idea as to why my many-to-many are duplicating?
{
"title": "A bigger descrption goes here I assum",
"summary": "A summary goes here?!?!?",
"description": "A bigger descrption goes here I assum",
"majorVersion": 10,
"minorVersion": 2,
"patchVersion": 11,
"features": [
"some feature",
"some feature",
"another feature",
"another feature"
],
"authorId": "00000000-0000-0000-0000-000000000000",
"id": "fd3ca365-7e5f-4d72-791f-08dac4c829fa",
"dateCreated": "0001-01-01T00:00:00",
"dateModified": "0001-01-01T00:00:00"
}
{
"title": "A bigger descrption goes here I assum",
"summary": "A summary goes here?!?!?",
"description": "A bigger descrption goes here I assum",
"majorVersion": 10,
"minorVersion": 2,
"patchVersion": 11,
"features": [
"some feature",
"some feature",
"another feature",
"another feature"
],
"authorId": "00000000-0000-0000-0000-000000000000",
"id": "fd3ca365-7e5f-4d72-791f-08dac4c829fa",
"dateCreated": "0001-01-01T00:00:00",
"dateModified": "0001-01-01T00:00:00"
}
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.