Code First和多对多关系

时间:2013-05-06 06:43:23

标签: entity-framework ef-code-first

希望有人可以告诉我如何实现这种多对多的关系...

我有两个班,车和车主。每辆车都可以由许多车主拥有。每个车主都可以拥有很多车。请注意,我只需要从汽车到所有者的导航属性。

public partial class Car
{
    public int CarId { get; set; }
    public string Name { get; set; }
    public ICollection<Owner> Owners { get; set; }
}

public partial class Owner
{
    public int OwnerId { get; set; }
    public string  Name { get; set; }
}

在我的DbInitializer中,我像这样播种b。

        Owner owner1 = new Owner() { OwnerId = 10, Name = "Erik" };
        context.Owners.Add(owner1);
        Car b1 = new Car() { CarId = 1, Name = "Volvo", Owners = new List<Owner>(new Owner[] { owner1 }) };
        Car b2 = new Car() { CarId = 2, Name = "Saab", Owners = new List<Owner>(new Owner[] { owner1 }) };
        context.Cars.Add(b1);
        context.Cars.Add(b2);
        context.SaveChanges();

结果是owner1只拥有b2。为什么?怎么能把它变成多对多的关系?

谢谢!

1 个答案:

答案 0 :(得分:2)

在你的上下文中添加:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<Car>().HasMany(c => c.Owners).WithMany();
}

我告诉EF,在Car中没有导航属性的OwnerOwner之间存在多对多关联。