Catalin
Catalin

Reputation: 11721

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?

Upvotes: 4

Views: 176

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364249

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. You must also change navigation properties in both Product and User to point to collection of ProductXUser. Direct many-to-many relation works only when you do not expose junction table as an entity.

Upvotes: 3

Related Questions