【问题标题】:One-to-many using EF5 fluent API一对多使用 EF5 fluent API
【发布时间】:2013-04-23 05:20:33
【问题描述】:

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

【问题讨论】:

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


    【解决方案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);
    

    【讨论】:

    • 谢谢。但不幸的是,这会在 Children 表中创建一个 FK。出于设计原因,我不想要这样的钥匙。然而,这将是正确的方法。
    • 第一种情况(Map)使用独立关联(因此,它不使用任何外键)。
    • 刚刚尝试确定,它在 Children 表中创建了一个 FK。如果您省略.Map(),那么它只是根据约定命名该键,但它就在那里。我不能有那把钥匙。我认为连接表是不可避免的,但我不知道如何让它表现得像 1:1。
    猜你喜欢
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 2013-02-01
    相关资源
    最近更新 更多