Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>When you use <code>[InverseProperty]</code> at both ends of a 1:1 association it is not clear who the principal should be. The principle is the entity the other end (the dependent) refers to by a foreign key. Even though you tell EF that <code>EditoredBy</code> and <code>CurrentlyWorkingBookId</code> both are part of one association it still would be possible to have a foreign key field for <code>EditoredBy</code> in <code>Book</code> (that wouldn't show in the class model).</p> <p>Admittedly, one could contend that you've told EF enough to create the database model properly. EF could have logic that says: if I've been told about one foreign key in a 1:1 association, then I know who the principle should be. However, unfortunately it doesn't.</p> <p>So I would use the fluent API to model this:</p> <pre><code>public class Author { public int AuthorId { get; set; } public ICollection&lt;Book&gt; Books { get; set; } public Book CurrentlyWorkingBook { get; set; } } public class Book { public int BookId { get; set; } public int AuthorId { get; set; } public Author Author { get; set; } public Author EditoredBy { get; set; } } </code></pre> <p>In <code>OnModelCreating</code>:</p> <pre><code>modelBuilder.Entity&lt;Author&gt;() .HasMany(a =&gt; a.Books) .WithRequired(b =&gt; b.Author) .HasForeignKey(b =&gt; b.AuthorId); modelBuilder.Entity&lt;Author&gt;() .HasOptional(a =&gt; a.CurrentlyWorkingBook) .WithOptionalDependent(b =&gt; b.EditoredBy) .Map(m =&gt; m.MapKey("CurrentlyWorkingBookId")); </code></pre> <p>Personally, I like the fluent API because the lambda expressions allow compile-time checks and it is much more conspicuous which ends comprise one association.</p> <p>As you see, <code>CurrentlyWorkingBookId</code> can not be part of the class model in this scenario. That is because an <code>OptionalNavigationPropertyConfiguration</code> (the return type of <code>WithOptionalDependent</code>) doesn't have <code>HasForeignKey</code> method. I'm not sure why not. I think it should be possible to set a primitive FK value (<code>CurrentlyWorkingBookId</code>) as well as a reference property (<code>CurrentlyWorkingBook</code>).</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.
    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