7

假设我们正在使用实体框架代码优先方法,并且我们有两个对象,它们通过两个一对多关系链接(一个Person可以拥有多个Cars,但每辆车都有一个所有者和一个“主驾驶员”) . 这是两个实体:

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
}

如何告诉实体框架应该使用两个外键(OwnerId或)中的哪一个来确定集合?我只是尝试用这两个实体自动创建一个数据库,它假设我出于某种原因想用作外键,而显然我想使用外键。MainDriverIdCarsOwnedMainDriverIdCarsOwnedOwnerId

4

1 回答 1

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);
   }
}
于 2012-11-09T16:49:16.183 回答