如何在实体框架中设置两个一对多关系?

时间:2012-11-09 15:58:25

标签: c# database entity-framework ef-code-first

假设我们正在使用实体框架代码优先方法,并且我们有两个与两个一对多关系链接的对象(一个Person可以拥有许多Car s,但每辆车都有车主和“主要驾驶员”)。以下是两个实体:

public class Person {
    #region Persisted fields
    [Required]
    public int PersonId { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string Surname { get; set; }
    #endregion

    #region Navigation properties
    public virtual ICollection<Car> CarsOwned { get; set; }
    #endregion
}

public class Car {
    #region Persisted fields
    [Required]
    public int CarId { get; set; }
    [Required]
    public string Make { get; set; }
    [Required]
    public string Manufacturer { get; set; }
    [Required]
    public string RegNo { get; set; }
    [Required]
    [ForeignKey("Owner")]
    public int OwnerId { get; set; }
    [Required]
    [ForeignKey("MainDriver")]
    public int MainDriverId { get; set; }
    #endregion

    #region Navigation properties
    public virtual Person Owner { get; set; }
    public virtual Person MainDriver { get; set; }
    #endregion
}

如何判断实体框架应该使用哪两个外键(OwnerIdMainDriverId)来确定CarsOwned集合?我刚尝试使用这两个实体自动创建数据库,并且由于某种原因我假设我想使用MainDriverId作为CarsOwned外键,显然我想使用{{1}外键。

1 个答案:

答案 0 :(得分:11)

我怀疑你必须使用流畅的配置进行设置。

public class YourContext : DbContext
{
   ...
   protected override OnModelCreating(DbModelBuilder modelBuilder)
   {
      modelBuilder.Entity<Car>()
         .HasRequired(c => c.Owner)
         .WithMany(p => p.CarsOwned)
         .HasForeignKey(c => c.OwnerId)
         .WillCascadeOnDelete(false);
          // Otherwise you might get a "cascade causes cycles" error

      modelBuilder.Entity<Car>()
         .HasRequired(c => c.MainDriver)
         .WithMany() // No reverse navigation property
         .HasForeignKey(c => c.MainDriverId)
         .WillCascadeOnDelete(false);
   }
}