1

使用 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(如果需要,如何定义?),还是有更简单的方法?

4

1 回答 1

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);
于 2013-04-29T13:56:39.597 回答