burakk
burakk

Reputation: 1291

EF Code First Many-to-Many Relationship with ASP.NET Identity Table at one Side

I am trying to accomplish many-to-many relationship using code-first EF with ASP.NET Identity table at one side. The join table is not generated in the DB, though. What am I missing? Here are my model classes:

AppUser.cs:

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

    public DateTime? LastSuccessfulLoginDate { get; set; }

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

and

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; }
}

Upvotes: 0

Views: 64

Answers (1)

Dei Revoledo
Dei Revoledo

Reputation: 175

In your dbcontext you can configure:

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");
                        });

}

Upvotes: 1

Related Questions