假设我们正在使用实体框架代码优先方法,并且我们有两个对象,它们通过两个一对多关系链接(一个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
}
如何告诉实体框架应该使用两个外键(OwnerId
或)中的哪一个来确定集合?我只是尝试用这两个实体自动创建一个数据库,它假设我出于某种原因想用作外键,而显然我想使用外键。MainDriverId
CarsOwned
MainDriverId
CarsOwned
OwnerId