Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I believe the following should work for you</p> <pre><code>public class Address { public int AddressId { get; set; } public string AddressString { get; set; } } public class User { public int UserId { get; set; } public virtual ICollection&lt;Address&gt; Addresses { get; set; } } public class House { public int HouseId { get; set; } public virtual Address Address { get; set; } } public class TestContext : DbContext { public DbSet&lt;Address&gt; Addresses { get; set; } public DbSet&lt;User&gt; Users { get; set; } public DbSet&lt;House&gt; Houses { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity&lt;User&gt;().HasMany(u =&gt; u.Addresses).WithMany(); modelBuilder.Entity&lt;House&gt;().HasRequired(h =&gt; h.Address).WithOptional().Map(m =&gt; m.MapKey("AddressId")); } } </code></pre> <p>Note that it's often better to specify the foreign key fields yourself, which can make life a lot easier for you later on. If you do this, then you can choose to rewrite House as the following:</p> <pre><code>public class House { public int HouseId { get; set; } public int AddressId { get; set; } public virtual Address Address { get; set; } } </code></pre> <p>Convention will link up AddressId and Address. If you have a one-to-one mapping between House and Address, you could also link them on their primary keys:</p> <pre><code>public class House { [ForeignKey("Address")] public int HouseId { get; set; } public virtual Address Address { get; set; } } </code></pre> <p>You mentioned that you would like to enforce at least one address - this isn't possible with a one-to-many relationship. You could only do this if a user had exactly one address, at which point you could add a required AddressId property on the User class.</p> <p>One other comment - you made everything virtual in your code. You only need to make navigation properties virtual.</p>
    singulars
    1. This table or related slice is empty.
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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