views:

44

answers:

4

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.

Help would be appreciated!

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

A: 

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.

Andrew Cooper
A: 

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.

Morteza Manavi
I don't have the profiler installed, and I don't see it as a feature I can add when re-running the setup, so sadly, that's a dead end. As far as `StoreGeneratedPatern`, I'm pretty sure I understood it correctly when I read up on it at MSDN. Unless *Identity* is intended only for PK columns and nothing else?
Alex
Either way, how do I overcome the issue of EF blocking database generated values?
Alex
Ok, first you need to tell me about your approach: Do you have an existing database and creating a model based on it or you are following a model-first approach?
Morteza Manavi
I have an existing database and I'm creating the model off of it.
Alex
+1  A: 

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.

Yakimych
In the context of my question, you have the best solution. It works like a charm. Thanks!
Alex
A: 

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.

Kristof Claes