Is my Entity Framework generated SQL executing twice?
Asked Answered
O

1

6

I'm looking at analysing the performance of the SQL generated from Entity Framework 1, using MS SQL 2008.

When I run a trace in SQL Server Profiler 2008, I noticed something that I didn't expect. For each query that gets executed, I get two RPC:Completed statements, separated by an exec sp_reset_connection statement. Is this the expected behavior?

SQL Server Profiler Results

Olio answered 6/3, 2012 at 12:40 Comment(5)
Can you post the code you are running?Leuctra
@ajcvickers The system I'm dealing with is rather large, so supplying the code as-is won't be possible, it will take me some time to get a prototype together. I take it that this is not what you'd expect either then?Olio
Every time a LINQ to Entities query is enumerated (e.g. with ToList()), then the query is executed against the database. I was wondering if it was this.Leuctra
are you binding it to a grid? I found when I bind a grid to a entity query without a .tolist() then it is executed several times.Watanabe
I'm not using a grid (I assume you mean a .net Data Grid or similar) - My presentation layer is built using .net MVC and I'm going through a Service Layer, which in tern uses a Repository. From your questions, it sounds as though you agree with me when you think my queries might be running twice - I'll do some serious investigation now..Olio
O
5

Answer: Yes

It turns out that it was a "feature" within AutoMapper that was causing my issue.

See here: When Mapping an IQueryable I see the database getting hit twice in my profiler.

Unfortunately because I'm using version 1.1 (.net 3.5) this doesn't look like it's going to get fixed.

Solution: call .ToList() on the IQueryable object before passing it into the Mapper.Map() method. Allowing the Mapper to enumerate the object causes a double execution.

Olio answered 24/4, 2012 at 15:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.