C
C#4mo ago
XZetkaX

Cannot add multiple same objects to DB, only distinct are saved. .NET EntityFramework

I have a template of exercise with name, description and amount of sets. I want to create multiple objects of Exercise * amount of sets. For example I have template [{ "name" : "Legs", "sets" : 3 }, { "name" : "Arms", "sets" : 2 } in DB I want to be saved [ {legs}, {legs}, {legs}, {arms}, {arms}], but only [{legs}, {arms}] are saved.
var exercises = planTemplate.Exercises
.SelectMany(x => Enumerable.Repeat(new Exercise
{
Name = x.Name,
Description = x.Description
}, x.Sets))
.ToList() ?? new List<Exercise>();

var plan = new FitnessPlan
{
TemplateId = planTemplate.Id,
Archived = false,
User = user,
Name = planTemplate.Name,
Exercises = exercises,
};

await _context.FitnessPlans.AddAsync(plan);
await _context.SaveChangesAsync();
var exercises = planTemplate.Exercises
.SelectMany(x => Enumerable.Repeat(new Exercise
{
Name = x.Name,
Description = x.Description
}, x.Sets))
.ToList() ?? new List<Exercise>();

var plan = new FitnessPlan
{
TemplateId = planTemplate.Id,
Archived = false,
User = user,
Name = planTemplate.Name,
Exercises = exercises,
};

await _context.FitnessPlans.AddAsync(plan);
await _context.SaveChangesAsync();
In attached screen they are all saved with exerciseId 1024 or 1025 instead of all be unique in range 1024-1028. In property exercises i have 5 objects without IDs but entityframework after saving changes gives them same IDs for objects with same structures, altho they are diffenent objeects.
No description
4 Replies
XZetkaX
XZetkaX4mo ago
GitHub
Fitness/API/Handlers/Plans/AddPlan/AddPlanQueryHandler.cs at main ·...
Contribute to NotZetka/Fitness development by creating an account on GitHub.
Unknown User
Unknown User4mo ago
Message Not Public
Sign In & Join Server To View
XZetkaX
XZetkaX4mo ago
I can't read what is written here?
Unknown User
Unknown User4mo ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server