Ok, I'm trying to figure out how to setup my DB properly.
I have two classes:
public class Event
{
public int EventId { get; set; }
public string EventName { get; set; }
}
and
public class Dog
{
public int DogId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
An event must be able to contain a collection of dogs. Every dog must be able to be part in any event. I'm guessing this is what they call a many-to-many relationship, but I do not now how to set it up with keys etc. I hope I'm clear enough with what I'm hoping to achieve.
I asked a similar question yesterday but I was then not clear over what I needed: Have a list of objects as a foreign key.
Thanks!
Yes, that is a N:N relationship. Assuming Code First, change your entities:
public class Event
{
public Event()
{
Dogs = new HashSet<Dog>();
}
public int EventId { get; set; }
public string EventName { get; set; }
public virtual ICollection<Dog> Dogs { get; set; }
}
public class Dog
{
public Dog()
{
Events = new HashSet<Event>();
}
public int DogId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public virtual ICollection<Event> Events { get; set; }
}
And your OnModelCreating
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Dog>()
.HasMany(d => d.Events)
.WithMany(e => e.Dogs)
.Map(m =>
{
m.MapLeftKey("DogId");
m.MapRightKey("EventId");
m.ToTable("DogEvent");
});
}
This should then create a junction table DogEvent
with just the two foreign keys, DogId
and EventId
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments