I am using ASP.NET 4.5, MVC5, C#, LINQ, EF6, SQL Server 2012/SQL Azure.
I need to significantly improve the efficiency of a complex query. In essence the purpose of the task is to copy a "sample" recordset with many child records. I am currently doing this via C# and LINQ. I suspect that I am requerying the database within multiple Foreach blocks, thus I am causing many calls to the database. While each query is small, the number of calls is not. It could be a 200+. I believe they call this is "N+1" problem.
The following layout gives an idea of the relationships and hence queries.
Table1-<Table1.1
-<Table1.2-<Table1.2.1
-<Table1.2.2-<Table1.2.2.1
-<Table1.2.2.2
Instead of using "Foreach" to bring back "Table1.1" etc, I want to bring back all related data in one hit to minimise the number of calls to the DB. I understand I need to use "Include". I have got as far as:
db.Table1.Where(r=>r.Id=myId).Include(x=>x.Table1.2).Include(x=>x.Table1.2)
However I am not sure how to alter this statement to bring back data down to "Table1.2.2.2". This is my question.
Thank you in advance.
EDIT 1
I found an initial answer.
db.Table1.Include(x=>x.Table1.1)
.Include(x=>x.Table1.2)
.Include(x=>x.Table1.2.Select(y=>y.Table1.2.1)
However I may not need the middle line, so the following may be fine.
db.Table1.Include(x=>x.Table1.1)
.Include(x=>x.Table1.2.Select(y=>y.Table1.2.1)
Thoughts...
EDIT2
I also need to go to 5 levels down. I am finding that this one retrieve times out !! Whether this is because EF is confused on the compilation, or that the retrieve is too complicated or both I am unsure. There is possibly a limit on how many levels one can use "Include" ? Also I am unsure that by specifying the path to the grandchildren then the parent are automatically retrieved, or do you have to specify the parents separately?