I've been re-examining the way I'm using entities and I need advice.
I'm creating a yoga booking service and each user will have a profile, spaces to meet up for yoga and events, with a date and time, for each space to meet up.
So my relationships look like this and they are all one-to-many
YogaProfile -> YogaSpace(s) -> YogaSpaceEvent(s)
When an event gets created, members (YogaProfiles
) can join anyone's event. Kind of like a class. It's a registering/scheduling system.
Initially I created a table called RegisterdStudents
and added the collection to YogaSpaceEvent
. Like this
public class YogaSpaceEvent
{
// other code here left out
public virtual ICollection<RegisteredStudent> RegisteredStudents { get; set; }
}
and RegisteredStudent
looks like this
public class RegisteredStudent
{
[Key]
public int RegisteredStudentId { get; set; }
[Index]
public int YogaSpaceEventId { get; set; }
[ForeignKey("YogaSpaceEventId")]
public virtual YogaSpaceEvent YogaSpaceEvent { get; set; }
[Index]
public int StudentId { get; set; }
}
This all works fine, but then I learned more about many-to-many and thought I might need to use it here being that many profiles can register for one event and many events can be registered to one profile ex. a class can have many attending and a student can attend many classes.
So I changed the code to make a many-to-many relationship by creating a virtual ICollection
on each of the two entities (YogaProfile
, YogaSpaceEvent
) and creating a join table called RegisteredStudentInEvent
like this
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<YogaProfile>()
.HasMany<YogaSpaceEvent>(x => x.YogaSpaceEvents)
.WithMany(x => x.RegisteredStudents)
.Map(x =>
{
x.MapLeftKey("YogaProfileId");
x.MapRightKey("YogaSpaceEventId");
x.ToTable("RegisteredStudentInEvent");
});
}
Now I can successfully add multiple students (YogaProfile
) to one class (YogaSpaceEvent
) and in the table I see the rows with the event (YogaSpaceEventId
) and who's registered (YogaProfileId
).
But now, looking at this many-to-many relationship setup, I see I'll NEVER need to add multiple classes (YogaSpaceEvent
) to a student (YogaProfile
) like below because YogaSpaceEvents
gets added to a collection on YogaSpaces
, not YogaProfile
yogaProfile.YogaSpaceEvents.Add(yogaSpaceEvent)
So my question is, should I go back to the initial way I was doing it or stay with this many-to-many model?? What's the difference, pro's, cons, etc?