Entity Framework Code First: One-to-Many and Many-to-Many relationships to same table

喜你入骨 提交于 2019-12-03 12:12:26

EF doesn't know where User.Events has to be mapped to. It could be Event.CreatedBy or it could be Event.Users. Both would result in a valid model. You must give EF a little hint what you want by applying the [InverseProperty] attribute:

public class User
{
    ...
    [InverseProperty("Users")]
    public virtual ICollection<Event> Events { get; set; }
    ...
}

With Code First Approach, I would always recommend to use fluent API rather than using DataAnnotations, Which uses some conversions automatically.

This way, you'll know what exact configuration you've made.

If I were you, here is what i would use :

public class EventMap : EntityTypeConfiguration<Event>
{
    public EventMap()
    {
        this.HasRequired(m => m.CreatedBy) // envent must have a creator
            .WithMany() // a user can have 0,1 or more events created by him
            .HasForeignKey(m => m.CreatedById) // specify property to be used as FK
            .WillCascadeOnDelete(true); // delete all events created by user if that specific user is deleted

        this.HasMany(m=>m.Users) // an event can have 0,1 or more participants
            .WithMany(m=>m.Events) // a user can be a participant in 0,1 or more events                
            .Map(m => m.MapLeftKey("EventId").MapRightKey("UserId")); // this will generate intermediate table to hold participant information - dbo.EventUser with EventId & UserId
            // Cascade Delete is always true for Many to Many mapping. however, it doesn't delete entry in other table, it deletes entry in Joined Table only.
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!