与Code First Entity Framework的单向多对多关系

时间:2011-11-15 12:01:44

标签: entity-framework-4.1

我是EF的新手,并试图通过代码优先方法获得多对多的单向关系。例如,如果我有两个类(不是我的真实模型),它们之间是N * N关系,但没有来自“Customer”方的导航属性。

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

映射代码看起来像......

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

这种语法迫使我对“Customer”实体使用“WithMany”。 以下url表示“按惯例,Code First总是将单向关系解释为一对多。”

是否可以覆盖它,还是应该使用任何其他方法?

1 个答案:

答案 0 :(得分:37)

使用此:

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

并将其映射到:

modelBuilder.Entity<User>()
    .HasMany(r => r.TaggedCustomers)
    .WithMany() // No navigation property here
    .Map(m =>
        {
            m.MapLeftKey("UserId");
            m.MapRightKey("CustomerId");
            m.ToTable("BridgeTableForCustomerAndUser");
        });