简体   繁体   中英

Timing Sql Queries with ADO.NET Entity Data Model

NET Entity Data Model in an Asp.net MVC web application. The database is up in Azure. I am trying to time my Sql Queries like this with the start and end time either side of the query.

start = DateTime.Now;
var query = item.Database.SqlQuery<CustomerQuery>(queryString);
end = DateTime.Now;

I am calculating the time it took like this

Duration = end.Subtract(start);

Now no matter how many results are being returned, sometimes in the thousands the time is practically the same.

Why is this? and is there a way of getting a more accurate time

Well, I'm not expert in this stack, but seems that SqlQuery returns DbRawSqlQuery object, that encapsulates the query, but doesn't execute it. As MSDN says "A DbRawSqlQuery object that will execute the query when it is enumerated."

So you should materialize the query, for example by calling ToList() .

var query = item.Database.SqlQuery<CustomerQuery>(queryString).ToList();

The DateTime.Now method is not the best way to clocking milliseconds, you can read more about it in the answer from Jon here . You should instead use the Stopwatch class which can be used like this.

using System.Diagnostics;

In the method

var sw = new Stopwatch();
sw.Start();
var query = item.Database.SqlQuery<CustomerQuery>(queryString);
sw.Stop();

var totalTime = sw.ElapsedMilliseconds;

If you are using Azure, you might also be able to tap into the Application Insights. You can configure your application to send information up to Azure.

See

https://azure.microsoft.com/en-gb/documentation/articles/sql-database-query-performance/ https://azure.microsoft.com/en-gb/documentation/articles/app-insights-asp-net/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM