Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I setup two one-to-many relationships in entity framework?
    primarykey
    data
    text
    <p>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 <code>Person</code> can own many <code>Car</code>s, but each car has an owner AND a 'main driver'). Here are the two entities:</p> <pre><code>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&lt;Car&gt; 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 } </code></pre> <p>How can I tell entity framework which of the two foreign keys (<code>OwnerId</code> or <code>MainDriverId</code>) should be used to determine the <code>CarsOwned</code> collection? I just tried auto-creating a database with these two entities, and it assumed that I wanted to use <code>MainDriverId</code> as the <code>CarsOwned</code> foreign key for some reason, when obviously I want to use the <code>OwnerId</code> foreign key.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload