繁体   English   中英

一对多使用EF5 Fluent API

[英]One-to-many using EF5 fluent API

使用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: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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM