Tuesday, 11 August 2015

Entity Framework SQL Generated Scripts Speed Gotcha

One day I was working with tables with non-unique primary keys and was able to use the Visual Studio Entity Model EDMX editor to generate the classes for me. I know in my gut-feeling that there could be something wrong with I am doing since when you are using Entity Framework your table should have a unique key identifier. Anyway I ignored this thought and proceeded - everything works well in terms of adding and using the generated classes however I noticed that the query (with a subquery on it) was taking really slow. If I re-encode the "equivalent" SQL query manually it run fast as it should be but if I run the TSQL query that EF generated behind-the-scene it was terribly slow.
Somehow the TSQL code that EF generated was not optimized at all - maybe because it doesn't have a unique identifier.

So what I did is I just didn't use EF for that project because I can't touch or add unique identifier on those tables that I need to use.