Reputation: 133
I have two entities. Event and User. I want to save the creator (= user) of the event as contact in my Event entity. Additionally i want to have several guides (= user as well) associated with my event.
This is (part of) my code:
public class User
{
public int ID { get; set; }
public string LoginName { get; set; }
public string DisplayName { get; set; }
public virtual ICollection<Event> Events { get; set; }
}
public class Event
{
public int ID { get; set; }
public string EventName { get; set; }
public User ContactName { get; set; }
public virtual ICollection<Room> Rooms { get; set; }
public virtual ICollection<User> Users { get; set; } // These are the guides
public virtual ICollection<Equipment> Equipments { get; set; }
[Required]
public EventType Type { get; set; }
}
I'm expecting EF6 (6.1.3) to create 1:n and n:m relationships between User and Event. What it does instead can be seen in the screenshot below:
There is one 1:n relation - as expected. But instead of one n:m relation there is one 1:n and one n:1 relationship. Please help.
Upvotes: 0
Views: 67
Reputation: 526
For many to many link, You have to write it in the function :
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany<Event>(s => s.Events)
.WithMany(c => c.Users)
.Map(cs =>
{
cs.MapLeftKey("UserRefId");
cs.MapRightKey("EventRefId");
cs.ToTable("UserEvent");
});
}
It's imply a new table between the two others
You can follow this guide
Upvotes: 2
Reputation: 6440
There isnt a foreign key relation mapped in Event class:
public class Event
{
public int ID { get; set; }
public string EventName { get; set; }
public int ContactId {get ; set;}
[ForeignKey("ContactId")]
public virtual User Contact { get; set; }
public virtual ICollection<Room> Rooms { get; set; }
public virtual ICollection<User> Users { get; set; } // These are the guides
public virtual ICollection<Equipment> Equipments { get; set; }
[Required]
public EventType Type { get; set; }
}
Upvotes: 0