Mapping many to many relationship

后端 未结 2 860
春和景丽
春和景丽 2021-01-22 05:00

I am have some trouble getting Entity Framework to handle a many to many relationship in my data schema. Here is my model:

public class User
{
    public int Us         


        
2条回答
  •  一向
    一向 (楼主)
    2021-01-22 05:31

    For your model you will need probably two one-to-many relationships and the following navigation properties:

    public class User
    {
        public int UserId { get; set; }
        public int Username { get; set; }
        // ...
        public ICollection CustomerUsers { get; set; }
    }
    
    public class Customer
    {
        public int CustomerId { get; set; }
        //...
        public ICollection CustomerUsers { get; set; }
    }
    
    public class CustomerUser
    {
        public int CustomerUserId { get; set; }
        public int CustomerId { get; set; }
        public int UserId { get; set; }
        public DateTime CreatedTimestamp { get; set; }
        //...
        public User User { get; set; }
        public Customer Customer { get; set; }
    }
    

    And the following mapping:

    modelBuilder.Entity()
        .HasRequired(cu => cu.User)
        .WithMany(u => u.CustomerUsers)
        .HasForeignKey(cu => cu.UserId);
    
    modelBuilder.Entity()
        .HasRequired(cu => cu.Customer)
        .WithMany(c => c.CustomerUsers)
        .HasForeignKey(cu => cu.CustomerId);
    

提交回复
热议问题