使用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
上定义一个唯一约束(如果是,如何?),还是有更简单的方法?
答案 0 :(得分:1)
但我想要1:n
使用WithRequired
或WithOptional
:
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);