Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to work with true self referencing entities in code first EF5?
    text
    copied!<p>There are a few questions out there on this topic, but my question is very specific to true self referencing. All the examples for other questions are circular references and that doesn't help me in this case.</p> <p>Lets say I have this model:</p> <pre><code>public class User { [Key] public int Id { get; set; } ... public int CreatedByUserId { get; set; } } </code></pre> <p>and this map:</p> <pre><code>public class UserMap : EntityTypeConfiguration&lt;User&gt; { public UserMap() { this.HasRequired(a =&gt; a.CreatedByUser) .WithMany() .HasForeignKey(u =&gt; u.CreatedByUserId); } } </code></pre> <p>After migrations generates a database with this code I can manually add a User in SQL Management Studio with Id = 1, and CreatedByUserId = 1 so that tells me that self references like this can work.</p> <p>However when using EF to create a user, I run into a "unable to determine a valid ordering for dependent operations" issue. There are a lot of questions on the matter that involve a new entity that refers another new entity that has a foreign key on the first entity, which is a circular reference. The solution in those cases is either save one of entities first or to have a nullable id on the circular entity foreign key. I can not do either of those because the first would be impossible and the second is a external constraint that I cannot have nullable ids.</p> <p>So, seeing how I can achieve this by adding a entry manually I can assume it's a limitation of EF5. What are the work arounds?</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