Mapping many to many relationship

后端 未结 2 861
春和景丽
春和景丽 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<CustomerUser> CustomerUsers { get; set; }
    }
    
    public class Customer
    {
        public int CustomerId { get; set; }
        //...
        public ICollection<CustomerUser> 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<CustomerUser>()
        .HasRequired(cu => cu.User)
        .WithMany(u => u.CustomerUsers)
        .HasForeignKey(cu => cu.UserId);
    
    modelBuilder.Entity<CustomerUser>()
        .HasRequired(cu => cu.Customer)
        .WithMany(c => c.CustomerUsers)
        .HasForeignKey(cu => cu.CustomerId);
    
    0 讨论(0)
  • 2021-01-22 05:37

    Instead of trying to map this as many to many, map it as two one to many relationships. See the discussion of many to many join tables with payload in Many-to-Many Relationships in this tutorial:

    http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-a-more-complex-data-model-for-an-asp-net-mvc-application

    0 讨论(0)
提交回复
热议问题