Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to view generated SQL from Entity Framework?

As the title says, how do I view the SQL generated by Entity Framework from within my code? I'm running into an error where the EF is crashing because a field is generated by the database (a DateTime field), and I thought I set it to know that the store is generating it via StoreGeneratedPattern, but it's still crashing, so I would like to see what exactly it's trying to push up to the database.

P.S. I've only been using EF for about an hour now... Switching from L2S.

like image 297
Gup3rSuR4c Avatar asked Oct 28 '10 01:10

Gup3rSuR4c


5 Answers

Since you don't have Sql Profiler, your best choice would be LINQPad. You can use your existing assembly.

Click Add connection -> Use a typed data context from your own assembly -> Entity framework and select your dll.

You can write queries directly against your model (or copy-paste from your code). Select the SQL 'tab' under the query window to view the generated SQL code.

like image 115
Yakimych Avatar answered Oct 13 '22 09:10

Yakimych


You can use the Entity Framework Profiler (EFProf). It's not free, but there's a 30-day trial available. It does a lot more neat stuff besides showing you the SQL statements.

like image 40
Kristof Claes Avatar answered Oct 13 '22 10:10

Kristof Claes


Generally, you should always use SQL Profiler to see the SQL statements that being submitted by EF into your database.

Also, I think you misunderstood about what StoreGeneratedPattern is. If you look at its possible values inside the model, you'll see that it has identity meaning that the value will be generated (by the database) when the row is inserted and will not otherwise change. The other options are Computed, which specifies that the value will be generated on inserts and updates, and None, which is the default.
So EF will not generate that DateTime field on the fly for you, you need to manually create it and then update your model from database so that EF will generate appropriate metadata to work with it at runtime.

like image 28
Morteza Manavi Avatar answered Oct 13 '22 09:10

Morteza Manavi


The free AnjLab Sql Profiler will work if real SQL Profiler is not available because you're using SQL Server Express: http://anjlab.com/en/projects/opensource/sqlprofiler. It's not quite as nice as the real thing but it gets the job done well enough.

like image 39
Scott Stafford Avatar answered Oct 13 '22 10:10

Scott Stafford


One solution would be to capture the network traffic and have a look at the data on that level. Microsoft Network Monitor does a good job of this.

Of course, that only works if you're using a separate DB server, and the connection is not encrypted.

like image 30
Andrew Cooper Avatar answered Oct 13 '22 10:10

Andrew Cooper