unidirectional many-to-many relationship with Code First Entity Framework

前端 未结 1 962
暖寄归人
暖寄归人 2020-12-14 08:30

I am new to EF, and trying to get many-to-many unidirectional relationship with code first approach. For example, if I have following two classes (not my real model) with b

相关标签:
1条回答
  • 2020-12-14 08:56

    Use this:

    public class User {
        public int UserId { get; set; }
        public string Email { get; set; }
        // You must use generic collection
        public virtual ICollection<Customer> TaggedCustomers { get; set; }
    }
    
    public class Customer {
        public int CustomerId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    

    And map it with:

    modelBuilder.Entity<User>()
        .HasMany(r => r.TaggedCustomers)
        .WithMany() // No navigation property here
        .Map(m =>
            {
                m.MapLeftKey("UserId");
                m.MapRightKey("CustomerId");
                m.ToTable("BridgeTableForCustomerAndUser");
            });
    
    0 讨论(0)
提交回复
热议问题