How to view generated SQL from Entity Framework? - 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.

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.

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.

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.

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.

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.

Related

Entity Framework SQL Profiler - How to trace back to code that generated SQL

We are using entity framework 6.0 for development of our new application. All of our entity queries are generated from a DAL layer. For our current applications that are deployed to production, we use a SQL monitoring tool to track the performance of SQL queries.
My concern is how will I track down the DAL class that is generating the SQL so, I can address performance issues with the entity query. All I have from the tool is the SQL query that was generated by entity framework.
How are others tracking down SQL query issues in production? I know I can use Glimpse but how can you track back to the entity framework query that generated the SQL if you just have the raw SQL? I tried using the predicate builder to add a dummy where clause to see if that would show up in the SQL but it is ignored. like
predicate = predicate.Or(u => "methodName" == "methodName");
Thanks for the help.
You could use New Relic to instrument the application and SQL. They have a feature called "Key Transactions" which can tell you the slow transactions (really set up just for web requests, but you can theoretically get it working for other types of apps) and allow you to see the slow SQL queries within those transactions.
In order to add your data access layer in to the methods being instrumented, you can edit the instrumentation xml files as per https://docs.newrelic.com/docs/dotnet/dotnet-agent-custom-metrics
Note that the Key Transactions feature is in the premium addition, which costs. You do get that free for a while, so it might be worth a look to see if it provides enough value to you.
(I have no affiliation with New Relic, by the way.)
If you have a test suite covering the code that generates the queries, you could use this to save the generated SQL queries out to file along with the DAL method that generated them. You could do this by using the following code (taken from this SO answer regarding viewing the SQL):
var result = from x in appEntities
where x.id = 32
select x;
var sql = ((System.Data.Objects.ObjectQuery)result).ToTraceString();
If you saved these queries and method names in some structured fashion (e.g. CSV), perhaps as a side effect of the test run, you might be able to do a reverse lookup by searching this file for the query you see from production. You might have to do some normalisation, e.g. strip out all non-significant whitespace and in both cases take out the parameter assignments.

Entity Framework Code First with an existing database

I have to create a new project and (as usual) is with an existing SQL Server database.
I used to use EF Code First connecting with my database, opening my EDMX model designer and then right click --> Add Code Generation Item. (http://weblogs.asp.net/jgalloway/archive/2011/02/24/generating-ef-code-first-model-classes-from-an-existing-database.aspx) Easy.
But now I've discovered there's something called EF Power Tools that allows me to do Reverse Engineer Code First (cool name!) and get the same (http://msdn.microsoft.com/en-us/data/jj200620)
Do you know the difference between the two options? Which one is better?
Thanks in advance.
(Sorry if this question was previously asked but I didn't find it.)
The difference is that the edmx approach is not code first, but database first with DbContext API. You will always use the database as the source of model changes.
EF Power Tools produce a truly code first model with DbContext: from then on you will change the class model first and modify the database accordingly (e.g. by EF migrations).
Neither is "better". DbContext API is easier to work with than ObjectContext, but both approaches use the former. It's up to you to choose whether you want to work database first or code first. It's a matter of personal preference and it may depend on who maintains the database structure. With database first it is easier to respond to changes someone else imposes on the database structure.
As far as workflow goes for database first, adding to what #Gert-Arnold said:
With database first it is easier to respond to changes someone else imposes on the database structure.
If someone else is managing the database changes, I'm finding it far easier to use the EF Designer. You get an updated database, then just right-click in the EF Designer and update the model from the database. You can use source control to easily view what has changed.
Also, if you only need a subset of tables from the database, reverse engineering causes alot of work having to go back and remove classes and properties from the context.
I found re-reverse engineering via code-first to an existing database to be just too much of a pain trying to figure out what changed and how I needed to update code that used the context.

EF Code first database generation

I have a MVC3 website I have been playing with, and the database is quite well populated. I need to change the underlying models, but of course, the standard approach would drop all data. Having the CREATE SQL (so I can ensure all fields/relationships are in line with the models), and the calculated hash (so EF thinks the models match the database) would allow me to manually make changes to the database.
Is there a way to interrogate a DataContext (or some other object) to:
1. Get the SQL it would use to generate the dataschema; and
2. Get the ERM Metadata hash
I have considered some other migration options, but just want to explore this avenue.
Edit: This is EF4.1, and is running against SQL 2008 R2 if that is of any relevance.
Thanks
Andrew
You can do it with EF Migrations. You'd need to upgrade your project to EF 4.3. You'd use the "Update-Database -Script" ps command.
Here is a link to the ASP.Net team blog on it: http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-code-based-migrations-walkthrough.aspx
Pluralsight also has a course on it. They also have a free trial. http://www.pluralsight-training.net/microsoft/Courses/TableOfContents?courseName=efmigrations

Does any one knows how to get sql statement in ado.net entity

How to get the exact sql query which is genarting at time of domaincontext.submitchanges() as i am getting validation error and not able to find where is the exact issues
Does any one knows how to get sql statement in ado.net entity
It would be great if you at least know what technology are you using. EF 4.1 doesn't have any SubmitChanges but Linq-to-Sql does.
How to get executed SQL in Linq-to-Sql: Use Log property or external profiler.
How to get executed SQL in EF: Use external profiler.
If you have parameters I don't think you can do it directly. You would need to cast everything to a string and build it yourself. I suppose being able to intercept the exact SQL statement going through the pipes is a security risk. At least that's the conclusion I came to when I tried to print the SQL statement I was sending out.

EF4, self tracking, repository pattern, SQL Server 2008 AND SQL Server Compact

I am creating a project using Entity Frameworks 4 and self tracking entities. I want to be able to either get the data from a sql server 2008 database or from sql server compact database (with the switch being in the config file). I am using the repository pattern and I will have the self tracking entities sitting in a separate assembly.
Do I need two edmx files? If so, how do I generate only one set of STE's in the separate assembly? Also do I need to generate two context classes as well? I am unsure of the plumbing for all this. Can anyone help?
Darren
I forgot to add that the two databases will be identical and that the compact version is for offline usage.
Just to follow up on this. In the end I had to maintain two separate edmx files, one for sql server and one for compact. The main reason being that compact 3.5 does not support auto identities (as mentioned above by Zeeshan). This in turn led to two context classes. In the context class for sql server compact I had to put code to check for insertions, query the database for the latest id and increment it manually before saving.
Thankfully with the release of compact 4.0 this no longer applies as it supports auto id and you can indeed use just one edmx file.
Darren
You do need the edmx file as long as the schema is exactly the same. just change the connectionstring and everything would work seamlessly. Though i am not sure how u are saying that schema is same when compact edition does not support identity concept and full blown sql server does. So if you are using features specific to sql server that's not available in compact, then you would get runtime errors.