-1

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.

Fragment of code

            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; }
    }
10
  • I've added code not as a picture and more explanation.
    – Zetka
    Commented Jul 8 at 12:24
  • When working with database, you MUST have a unique key column. Then you can can have several rows, all with its own key.
    – Poul Bak
    Commented Jul 8 at 12:46
  • Exercises table has primaryKey Id
    – Zetka
    Commented Jul 8 at 13:07
  • You don't set that key, is it auto incremented?
    – Poul Bak
    Commented Jul 8 at 13:14
  • Just checked your screenshot, they have THE SAME id, that's why it fails.
    – Poul Bak
    Commented Jul 8 at 13:16

1 Answer 1

1

Problem that Enumerable.Repeat returns the same object instance for each set and your exercises collection become filled with one object. You should change it to Enumerable.Range

var exercises = planTemplate.Exercises
    .SelectMany(x => Enumerable.Range(1, x.Sets)
        .Select(_ => new Exercise
        {
            Name = x.Name,
            Description = x.Description
        })
    ).ToList();
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.