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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With