[英]How do I setup two one-to-many relationships in entity framework?
Let's say we're using an entity framework code-first approach, and we have two objects that are linked with two one-to-many relationships (one Person
can own many Car
s, but each car has an owner AND a 'main driver'). 假设我们使用实体框架代码优先方法,并且我们有两个对象与两个一对多关系链接(一个
Person
可以拥有许多Car
,但每辆汽车都拥有一个所有者和一个'主要驱动程序“)。 Here are the two entities: 以下是两个实体:
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
}
How can I tell entity framework which of the two foreign keys ( OwnerId
or MainDriverId
) should be used to determine the CarsOwned
collection? 如何判断实体框架应该使用哪两个外键(
OwnerId
或MainDriverId
)来确定CarsOwned
集合? I just tried auto-creating a database with these two entities, and it assumed that I wanted to use MainDriverId
as the CarsOwned
foreign key for some reason, when obviously I want to use the OwnerId
foreign key. 我刚尝试用这两个实体自动创建一个数据库,并且由于某种原因我假设我想使用
MainDriverId
作为CarsOwned
外键,显然我想使用OwnerId
外键。
I suspect you'll have to use the fluent configuration to set this up. 我怀疑你必须使用流畅的配置进行设置。
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.