使用EF5流畅API的一对多

时间:2013-04-29 13:51:04

标签: c# entity-framework entity-framework-5 poco

使用EF5,我想要Car:Wheel == 1:0..n

的一对多映射
public class Car {
  public int ID { get; set; }
  public virtual ICollection<Wheel> Wheels { get; set; }
}

public class Wheel {
  public int ID { get; set; }
  // I don't want to define a reverse relationship here
}

所以对于Car我做了:

modelBuilder.Entity<Car>()
  .HasMany(x => x.Wheels)
  .WithMany()
  .Map(x => x
    .MapLeftKey("CarID")
    .MapRightKey("WheelID")
    .ToTable("Car_Wheel"));

这给了我一个n:n联接表。但我想要1:n

我是否需要在Car_Wheel.CarID上定义一个唯一约束(如果是,如何?),还是有更简单的方法?

1 个答案:

答案 0 :(得分:1)

  

但我想要1:n

使用WithRequiredWithOptional

modelBuilder
            .Entity<MyParentEntity>()
            .HasMany(_ => _.Children)
            .WithRequired() //.WithOptional()
            .Map(/* map association here */);

但是如果你使用外键关联会更好:

public class Wheel 
{
  public int ID { get; set; }
  public int CarID { get; set; }
}

modelBuilder
    .Entity<MyParentEntity>()
    .HasMany(_ => _.Children)
    .WithRequired() //.WithOptional()
    .HasForeignKey(_ => _.ParentId);