Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF/LINQ How to include child entities when there is a bidirectional relation

Environment

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.

Context

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.

The code

Here is my code to call EntityA with its EntityB children.

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;
}

The error

System.StackOverflowException {Cannot evaluate expression because the current thread is in a stack overflow state.}

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.

My solutions or alternatives

  • 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.
  • Avoid using include, load separately the EntityA and push it into the Navigation property of my EntityB that refers to my EntityA.

the question

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.

I Thank you for your time

Ian

like image 843
Segers-Ian Avatar asked Oct 02 '12 11:10

Segers-Ian


1 Answers

I tried to reproduce your problem in EF 5 (Visual Studio 2012) and I don't get any errors. Is there anything else that could cause your problem? Is it working with a simple POCO setup?

I also wanted to note that STE's can give you quite a headache. I have worked with STE before and now I'm really trying to avoid them. Are you sure you want to use STE?

Instead of using STE's you can use plain old DTO's. You will keep your rich domain model on the server and only send the data that is necessary to the client. This way you can create tailored DTO's with the least amount of data for each use case.

like image 109
Wouter de Kort Avatar answered Sep 22 '22 06:09

Wouter de Kort