2017-04-09 106 views
0

我嘗試使用代碼優先的EF與ASP.NET身份表在一側實現多對多關係。不過,數據庫中並未生成連接表。我錯過了什麼?這裏是我的模型類:EF代碼與ASP.NET身份表的首次多對多關係

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

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

} 
+0

謝謝你,但這是流利的API。我如何在Code First中配置? – burakk

+0

兩者都是代碼首先你可以先用流利的API或數據註釋代碼 –

+0

是的,我知道,我的意思是數據註釋。我想知道爲什麼EF不首先創建連接表而不需要Fluent API。 – burakk