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();
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 withoud IDs but entityframework after saving changes gives them same IDs for objects with same structures, altho they are diffenent objeects.
FitnessPlan class
public class FitnessPlan
{
public int Id { get; set; }
public int TemplateId { get; set; }
public bool Archived { get; set; }
public int UserId { get; set; }
public AppUser User { get; set; }
public string Name { get; set; }
public IEnumerable<Exercise> Exercises { get; set; }
}
a unique key column
. Then you can can have several rows, all with its own key.