simon
simon

Reputation: 140

Multiple Many-to-Many relationsship Entity Framework

The main goal is the ability to have a many to many relationship between the table Mucle and Exercise. I want an Exercise to have both a primary and a secodary muscle group.

Is it possible to have two icollections in one model and only one in the other? If someone could help with the "fluent configuration" as well, I would appreciate it!

Here is the code I have got right now.

public class Muscle
    {
        public int MuscleID { get; set; }
        public bool IsFront { get; set; }
        public string Name { get; set; }

        public virtual ICollection<Exercise> Exercises { get; set; }
    }

    public class Exercise
    {
        public int ExerciseID { get; set; }
        // ExerciseCategory
        public int ExerciseCategoryID { get; set; }
        public DateTime CreationDate { get; set; }
        public string Description { get; set; }
        public string Name { get; set; }

        public virtual ExerciseCategory ExerciseCategory { get; set; }
        public virtual ICollection<Muscle> Muscles { get; set; }
        public virtual ICollection<Muscle> MusclesSecondary { get; set; }
    }

Upvotes: 2

Views: 138

Answers (1)

bubi
bubi

Reputation: 6491

No way to map the model you described.
To map your model (2 n-m relationship) you would need a Junction table with a discriminator and you can't do it with EF.

You have several way to change your model to make it work with EF

  • You create a model (a class) for the Junction table and insert a discriminator in it. Your model changes (and I think that the new model is less clear)
  • Why is there a Muscles and MusclesSecondary? Can it be discriminated with an attribute of Muscle? In this case you can have the attribute in Muscle and remove Exercise.MusclesSecondary Then you have only an n-m relationship that EF handles with a Junction table.
  • If you want this model you can add 2 collections to Muscle (for example ExcercisesMuscle and ExercisesMusclesSecondary) and a 3rd not mapped collection where you have the content of ExcercisesMuscle and ExercisesMusclesSecondary toghether. About the ExcercisesMuscle and ExercisesMusclesSecondary they can be observable collections so you can cache the content of Exercises collection in an efficient way.

Upvotes: 1

Related Questions