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

C# 如何在实体框架中设置两个一对多关系?,c#,database,entity-framework,ef-code-first,C#,Database,Entity Framework,Ef Code First,假设我们使用的是实体框架代码优先的方法,我们有两个对象,它们通过两个一对多关系链接(一个人可以拥有多辆车,但每辆车都有一个车主和一个“主司机”)。以下是两个实体: public class Person { #region Persisted fields [Required] public int PersonId { get; set; } [Required] public string FirstName { get; set; } [Re

假设我们使用的是实体框架代码优先的方法,我们有两个对象,它们通过两个一对多关系链接(一个
人可以拥有多辆
车,但每辆车都有一个车主和一个“主司机”)。以下是两个实体:

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
}
公共类人物{
#区域持久化字段
[必需]
公共int PersonId{get;set;}
[必需]
公共字符串名{get;set;}
[必需]
公共字符串姓氏{get;set;}
#端区
#区域导航属性
公共虚拟ICollection已加密{get;set;}
#端区
}
公车{
#区域持久化字段
[必需]
public int CarId{get;set;}
[必需]
公共字符串Make{get;set;}
[必需]
公共字符串制造商{get;set;}
[必需]
公共字符串RegNo{get;set;}
[必需]
[外国钥匙(“所有人”)]
public int OwnerId{get;set;}
[必需]
[外键(“主驱动程序”)]
public int MainDriverId{get;set;}
#端区
#区域导航属性
公共虚拟人所有者{get;set;}
公共虚拟人主驱动程序{get;set;}
#端区
}

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

我怀疑您必须使用fluent配置来设置它

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);
   }
}
public类YourContext:DbContext
{
...
模型创建时受保护的覆盖(DbModelBuilder modelBuilder)
{
modelBuilder.Entity()
.HasRequired(c=>c.Owner)
.有许多(p=>p.CarsOwned)
.HasForeignKey(c=>c.OwnerId)
.WillCascadeOnDelete(假);
//否则,可能会出现“级联导致循环”错误
modelBuilder.Entity()
.HasRequired(c=>c.MainDriver)
.WithMany()//无反向导航属性
.HasForeignKey(c=>c.MainDriverId)
.WillCascadeOnDelete(假);
}
}

这不是2对多的关系,你有2对1对多的关系。好吧,很公平,我会换个术语。