EF代码首先与ASP.NET身份表的多对多关系

时间:2017-04-09 18:11:26

标签: c# asp.net asp.net-mvc entity-framework ef-code-first

我试图在一侧使用代码优先EF和ASP.NET身份表来实现多对多关系。但是,不会在DB中生成连接表。我错过了什么?这是我的模型类:

AppUser.cs:

public class AppUser : IdentityUser
{
    public AppUser()
    {
        Notes = new HashSet<Note>();
    }

    public DateTime? LastSuccessfulLoginDate { get; set; }

    public virtual ICollection<Note> Notes { get; set; }
}

Note.cs:

public class Note
{
    public Note() {

        NoteAssignedToUsers = new HashSet<AppUser>();
    }

    [Key]
    public int NoteID { get; set; }

    [Required]
    public int FileID { get; set; }

    [Required]
    public string Content { get; set; }

    [Required]
    public Importance? Importance { get; set; }

    [Required]
    [DisplayFormat(DataFormatString = "{0:dd.MM.yyyy HH.mm}")]
    public DateTime AddedOn { get; set; }

    [Required]
    public string CreatorID { get; set; }

    [ForeignKey("FileID")]
    public virtual OAFile OAFile { get; set; }

    [ForeignKey("CreatorID")]
    public virtual AppUser CreatedBy { get; set; }

    public virtual ICollection<AppUser> NoteAssignedToUsers { get; set; }
}

1 个答案:

答案 0 :(得分:1)

在dbcontext中,您可以配置:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

    modelBuilder.Entity<Note>()
                .HasMany<AppUser>(s => s.NoteAssignedToUsers )
                .WithMany(c => c.Notes)
                .Map(cs =>
                        {
                            cs.MapLeftKey("AppUserId");
                            cs.MapRightKey("NoteId");
                            cs.ToTable("AppUsersNotes");
                        });

}