Note that there are some explanatory texts on larger screens.

plurals
  1. POEF/LINQ How to include child entities when there is a bidirectional relation
    text
    copied!<p><strong>Environment</strong></p> <p>I am using Entity Framework 5 on Framework 4.0. (This means I am actually using EF 4.4). As entities I use STE (Self Tracking Entities) because I am working in an N-Tier application. We use a database driven approach because EF was introduced later in the game.</p> <p><strong>Context</strong></p> <p>I have 2 Entities that both have a navigation property to each other. (EntityA has a navigation property to EntityB, and EntityB one to EntityA). The relation is 'EntityA > One-TO-Many > EntityB'. When I want to load the child Entities via a LINQ expression, I need to use INCLUDE (STE => Eager Loading) because I will pass all data trough several tiers.</p> <p><strong>The code</strong></p> <p>Here is my code to call EntityA with its EntityB children.</p> <pre><code>using (var ctx = new MyEntities()) { var result = (from s in ctx.EntityA.Include("EntityB") where s.Id = 11111 orderby s.TimeUpdated descending select s) .Take(10) .ToList(); return result; } </code></pre> <p><strong>The error</strong></p> <blockquote> <p>System.StackOverflowException {Cannot evaluate expression because the current thread is in a stack overflow state.}</p> </blockquote> <p>There is no error when I remove the 'INCLUDE'. I guess the reason is straightforward. I Want to load EntityA with child records EntityB, EntityB records wants to load its parent EntityA everytime, and EntityA ... I guess everyone understands the infinite loop here.</p> <p><strong>My solutions or alternatives</strong></p> <ul> <li>I go to my EDMX file and remove the navigation property for EntityA in EntityB. If I now want to load data about EntityA while I have an EntityB to my disposal. I need to do a separate DB request and I have 2 different objects that I have to pass on trough my tiers.</li> <li>Avoid using include, load separately the EntityA and push it into the Navigation property of my EntityB that refers to my EntityA. </li> </ul> <p><strong>the question</strong></p> <p>Are there better alternatives or approaches to fix this in my situation ? Should I go on with one of my alternatives I proposed or not? Because I was hoping for a better and cleaner solution.</p> <p>I Thank you for your time</p> <p>Ian</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