简体   繁体   English

EF Code First使用现有映射类进行多对多映射

[英]EF Code First Many to Many mapping using existing mapping class

I have three classes 我有三节课

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<User> Users { get; set; }
}

public class ProductXUser // Mapping class
{
    public int Id { get; set; }
    public int User_Id { get; set; }
    public int Product_Id { get; set; }
    public DateTime DateMapped { get; set; }
}

How can i map a many to many relationship (using Fluent API) between User class and Product class using ProductXUser class as the mapping table? 如何使用ProductXUser类作为映射表,在User类和Product类之间映射多对多关系(使用Fluent API)?

You can't. 你不能。 Once you expose junction table as entity you cannot use many-to-many relation. 将联结表公开为实体后,就无法使用多对多关系。 You must instead use two one-to-many relations. 您必须使用两个一对多关系。 One from User to ProductXUser and second from Product to ProductXUser . 一个从UserProductXUser ,第二个从ProductProductXUser You must also change navigation properties in both Product and User to point to collection of ProductXUser . 您还必须在ProductUser更改导航属性以指向ProductXUser集合。 Direct many-to-many relation works only when you do not expose junction table as an entity. 仅当您不将联结表公开为实体时,直接多对多关系才有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM