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

試著忘記壹切 提交于 2019-12-03 18:57:40

问题


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 be a N * N relationship between them, but no navigation property from "Customer" side.

public class User {
   public int UserId { get; set; }
   public string Email { get; set; }
   public ICollection TaggedCustomers { get; set; }
}
public class Customer {
  public int CustomerId { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
}

The mapping code looks like ...

modelBuilder.Entity()
        .HasMany(r => r.TaggedCustomers)
        .WithMany(c => c.ANavgiationPropertyWhichIDontWant)
        .Map(m =>
        {
            m.MapLeftKey("UserId");
                m.MapRightKey("CustomerId");
                m.ToTable("BridgeTableForCustomerAndUser");
        });

This syntax force me to have "WithMany" for "Customer" entity. The following url, says "By convention, Code First always interprets a unidirectional relationship as one-to-many."

Is it possible to override it, or should I use any other approach?


回答1:


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");
        });


来源:https://stackoverflow.com/questions/8136026/unidirectional-many-to-many-relationship-with-code-first-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!