Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>EF Code First supports <code>1:1</code> and <code>1:0..1</code> relationships. The latter is what you are looking for ("one to zero-or-one").</p> <p>Your attempts at fluent are saying <strong>required on both ends</strong> in one case and <strong>optional on both ends</strong> in the other.</p> <p>What you need is <em>optional</em> on one end and <em>required</em> on the other.</p> <p>Here's an example from the Programming E.F. Code First book </p> <pre><code>modelBuilder.Entity&lt;PersonPhoto&gt;() .HasRequired(p =&gt; p.PhotoOf) .WithOptional(p =&gt; p.Photo); </code></pre> <p>The <code>PersonPhoto</code> entity has a navigation property called <code>PhotoOf</code> that points to a <code>Person</code> type. The <code>Person</code> type has a navigation property called <code>Photo</code> that points to the <code>PersonPhoto</code> type.</p> <p>In the two related classes, you use each type's <em>primary key</em>, not <em>foreign keys</em>. i.e., you won't use the <code>LoyaltyUserDetailId</code> or <code>PIIUserId</code> properties. Instead, the relationship depends on the <code>Id</code> fields of both types. </p> <p>If you are using the fluent API as above, you do not need to specify <code>LoyaltyUser.Id</code> as a foreign key, EF will figure it out. </p> <p>So without having your code to test myself (I hate doing this from my head)... I would translate this into your code as</p> <pre><code>public class PIIUser { public int Id { get; set; } public LoyaltyUserDetail LoyaltyUserDetail { get; set; } } public class LoyaltyUserDetail { public int Id { get; set; } public double? AvailablePoints { get; set; } public PIIUser PIIUser { get; set; } } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity&lt;LoyaltyUserDetail&gt;() .HasRequired(lu =&gt; lu.PIIUser ) .WithOptional(pi =&gt; pi.LoyaltyUserDetail ); } </code></pre> <p>That's saying LoyaltyUserDetails <code>PIIUser</code> property is <em>required</em> and PIIUser's <code>LoyaltyUserDetail</code> property is optional.</p> <p>You could start from the other end:</p> <pre><code>modelBuilder.Entity&lt;PIIUser&gt;() .HasOptional(pi =&gt; pi.LoyaltyUserDetail) .WithRequired(lu =&gt; lu.PIIUser); </code></pre> <p>which now says PIIUser's <code>LoyaltyUserDetail</code> property is optional and LoyaltyUser's <code>PIIUser</code> property is required.</p> <p>You always have to use the pattern HAS/WITH.</p> <p>HTH and FWIW, one to one (or one to zero/one) relationships are one of the most confusing relationships to configure in code first so you are not alone! :)</p>
 

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