Create code first, many to many, with additional fields in association table

前端 未结 6 1660
星月不相逢
星月不相逢 2020-11-21 10:21

I have this scenario:

public class Member
{
    public int MemberID { get; set; }

    public string FirstName { get; set; }
    public string LastName { get         


        
6条回答
  •  攒了一身酷
    2020-11-21 10:51

    I'll just post the code to do this using the fluent API mapping.

    public class User {
        public int UserID { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
    
        public ICollection UserEmails { get; set; }
    }
    
    public class Email {
        public int EmailID { get; set; }
        public string Address { get; set; }
    
        public ICollection UserEmails { get; set; }
    }
    
    public class UserEmail {
        public int UserID { get; set; }
        public int EmailID { get; set; }
        public bool IsPrimary { get; set; }
    }
    

    On your DbContext derived class you could do this:

    public class MyContext : DbContext {
        protected override void OnModelCreating(DbModelBuilder builder) {
            // Primary keys
            builder.Entity().HasKey(q => q.UserID);
            builder.Entity().HasKey(q => q.EmailID);
            builder.Entity().HasKey(q => 
                new { 
                    q.UserID, q.EmailID
                });
    
            // Relationships
            builder.Entity()
                .HasRequired(t => t.Email)
                .WithMany(t => t.UserEmails)
                .HasForeignKey(t => t.EmailID)
    
            builder.Entity()
                .HasRequired(t => t.User)
                .WithMany(t => t.UserEmails)
                .HasForeignKey(t => t.UserID)
        }
    }
    

    It has the same effect as the accepted answer, with a different approach, which is no better nor worse.

提交回复
热议问题