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'). 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? 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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With