Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Cars, 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.

like image 432
Jez Avatar asked Nov 09 '12 15:11

Jez


1 Answers

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);
   }
}
like image 167
Richard Deeming Avatar answered Sep 21 '22 10:09

Richard Deeming