How to analyse LINQ queries - asp.net

I swear I've seen how to do this before, but now that I actually need to do it I can't remember where I saw it at. I need two different things --
1) to see the actual SQL query that is generated by a LINQ query and
2) when the SQL query actually hits the database to do whatever (CRUD operations)
Is there a tool that will allow me to do this?
EDIT:
Sorry, should have given more detail.
-- LINQ to Entities is what I'm using.
-- Also, I don't have admin rights on our instance of SQL Server, so I can't use SQL Profiler. I could always call the DBA and have them do it for me, but it's a hassle. I should have mentioned that and I apologize. What I really want is a tool that I can use on my own box that will allow me to see when a LINQ query hits the database while I am in debug mode (debugging and stepping through the code).

Try using SQL Profiler. It's great for seeing what LINQ to SQL is generating.
SQL Profiler is a graphical tool that allows system administrators to monitor events in an instance of Microsoft® SQL Server™. You can capture and save data about each event to a file or SQL Server table to analyze later. For example, you can monitor a production environment to see which stored procedures are hampering performance by executing too slowly.
LINQPad is also a great tool for writing linq and sql statements for testing.
LINQPad compiles your queries using .NET's CSharpCodeProvider (or VBCodeProvider). Because C# and VB are statically typed, any database objects that you reference need the backing of a typed DataContext. For performance, LINQPad builds typed DataContexts on the fly using Reflection.Emit rather than generating and compiling source code. It uses LINQ to SQL rather than Entity Framework because LINQ to SQL is an order of magnitude faster in building the metamodel when instantiated.

The .ToString() on the IQueryable for LINQ to SQL will show you the query.
var myquery = from x in dbcontext.MyTable
where x.Prop1 == someValue
select new {
value1 = x.prop1,
value2 = 5,
};
var sqlstring = myquery.ToString(); //<= look in this string

There are a few tools that can help.
L2SProf (Linq2Sql Profiler) is a for pay tool that can do a lot to help you see and optomize your queries. http://l2sprof.com/
LinqPad is a great tool for write linq to sql queries and seeing the sql that comes out. It also lets you write c# code just to experiment with things. It's a great coding scratch pad. There is a free version, but you get extra features if you pay. http://www.linqpad.net/
Otherwise, there are instructions here for viewing the generated sql for free with builtin stuff: http://msdn.microsoft.com/en-us/library/bb386961.aspx

Using Visual Studio 2010, turn on IntelliTrace and you'll see every request for LINQ To SQL, LINQ To Entities and generally everything that ultimately uses ADO.NET.

Are you looking for the DataContext.Log property? (I'm assuming you're using LINQ to SQL.)
You could create a TextWriter which dumped a stack trace and timestamp every time it was written to, which would give you the timing information.

depends entirely on the ORM. Most ORMs offer some sort of Log property you can plug a TextWriter or so into. Consult the docs for ORM to learn more.
In general: when you use some sort of SaveChanges method. This ties in with (1), the logger will provide you with the information.

Here is a solution, it is very complex: http://blogs.msdn.com/b/jkowalski/archive/2009/06/11/tracing-and-caching-in-entity-framework-available-on-msdn-code-gallery.aspx

Related

ASP.NET - Is there an object that I can execute sql queries against?

I'm developing an application in asp.Net using VB and an Access database. My client has specified these, and I can't use more robust tools.
My application has to perform a sizable number of logical operations, and SQL is perfect for this. However, because of some of the limitations of Access SQL, I can't really write large SQL statements that do the whole job. Lacking logic testing like IF-ELSE, I'm stuck writing literally dozens of SQL statements. That would be OK, but I'm leery of all that activity against an Access database. Access isn't very stable when you work it that hard.
I've fooled around with funky solutions using things like the SWITCH function, but they look more like spaghetti than actual code. Wouldn't be maintainable at all.
I can upload all of the data into objects in memory and loop back and forth through them using VB logic, but SQL would sure be more efficient.
My question is: is there some object I can create in memory that I can run SQL against? Some recordset-kind of thing? Came up snake-eyes when I searched for this, but I thought I'd ask.
Thanks for any suggestions.
So if I understand your question correctly you currently have to use an Access database as the backend storage but you do not like doing this and would rather pull all data into the application (ASP.Net) and perform your queries against this as if the database was an SQL database in the application. I expect then that you would push the data back.
AFAIK no this cannot be done. While you could put most of the data into objects and do the manipulation there you will not have the relationships etc. but you could try using LINQ or entity framework.
This link below explains that you can do LINQ with MSAccess and that may give you the query power you want.
Query Microsoft Access MDB Database using LINQ and C#

ADO.NET Entity Framework better than the method I am using?

I have read a bit about ADO.NET Entity Framework, but there is some things I am missing. Right now (not using EF, not sure what this technique is called, just ADO.NET?) we store all procedures in the database, that way if we have to change anything we have to just go into the db and change a query, pretty easy (other than the fact I have 100s of queries).
If I am correct with EF, I can query easier (no joins, shorter queries) but everything is saved in the Entity Data Model. So if I needed to change a query I would have to launch VS go in, find the location and change the query (which I guess would be linq-to-sql or Entity SQL to perform the query)
I just need some clarification about EF, and Entity SQL vs Linq-to-SQL.
Thank you!
When using EF you can use several types of data accessing:
Enity SQL - it is syntax similar to common SQL but queries are directly in code or entity model. If you want to change query you must rebuild and redeploy application.
Linq-to-entities - Linq queries on top of entity model. Again if you want to change query you must rebuild and redeploy application.
Executing stored procedures imported to model (also known as function import) - this is just sotred procedure exposed on your ObjectContext as .NET function. EF will handle parameters and result mapping.
Executing direct SQL by ExecuteStoreQuery or ExecuteStoreCommand (only EFv4). Here you can call any SQL including stored procedures.
So with EF you have both your current approach plus EF itself. Moreover calling native SQL through EF has some advantages like automatic mapping to prepared classes.
Anyway what you describe is quite uncommon situation. In many companies modifying something in DB requires same process as modifying application (or even more complicated) so you can't simply go and modify stored procedure in production.

Linq vs Stored Procedure

Which one is preferable for Enterprise CMS development:
LINQ or SP?
Generally what I do is LINQ to Views and LINQ to Stored Procedures. It's not a question of what is preferred because LINQ solves how to manage the data once it's queried where Stored Procedures are run on the SQL side to allow for query manipulation (or for me, mostly saving) of data which takes away from having the code to do it which is slower.
I would say you would want to use both if necessary. Are you saving to Entities that require multiple tables saves as one Entity? If so, use Stored Procedures with LINQ. If you're using 1 to 1 Entity relations to your tables then just use LINQ.
Stored Procedures can be used with Linq2Sql (and Entity Framework), so it isn't a choice of one or another.
I would cache the results from the database for a CMS as you likely to get the same data requested over and over again (cache the dataset, or use page caching, or cache the objects if using LINQ).
Then it doesn't matter if you use LINQ or an SP, but I would just use LINQ.
For simple CRUD table(no joins !!!) operations LINQ to SQL is fine, however for anything more complex (needing joins) I always use stored procedures (you can use Linq to stored procedures if you wish)
There are numerous debates around this on this site and others. For me, you can normally split the pro Linq camp into guys who have recently come into programming and have not had the history of having to use Stored procedures, ie not been heavily involved in the database side of previous projects.
Form my experience of working on several projects using pure LINQ, stored procedures and a mixture of both these are the two reasons I would stick to Linq for basic CRUD and stored procedures for anything more complex or relying on performance.
1 - Deploymenty/Security - Anyone that has worked in the real world a knows full well that having the database logic separated into stored procedures and not incorporated into the source code and released DLL is a massive advantage. You can add a proper security/access layer around each query using roles and SQL server security, imperative for any serious enterprise level company, and you can also make changes to the SQL of any stored procedure without having to do a new release of the main application (dll). I dont care how good you claim to be we have all had to fix live issues and performance bottlenecks using stored procedures and having to do this with a new application release would have been a nightmare.
2 - Performance/Code Smells - I have seen so many applications littered with huge amount of of badly written and inefficient Linq. Developers get lazy with Linq, little hidden lazy Linq to SQL queries which cause you a nightmare trying to debug performance issues on an enterprise level system - the motto 'get it done as quick as possible' seems prevalent. I have seen more Spaghetti code since the advent of Linq than I had seen with any previous class library/pattern Microsoft have released since COM.

Best Data Access Methods for New Web Application

I'm building a new web application project and am confused by the numerous methods of performing data access. I'm backending on SQL and a bit confused whether to use LINQ to SQL or trtaditional ADO.net ?
what are the advantages and disadvantages of using LINQ/SQL over ADO.net?
If it is ADO.net,then what is the best way to retrieve data means either calling the stored procedures or directly calling the t-sql code?
My question is what is cleanes and most effiecient and professional way of creating DAL for webapplication in asp.net?
Thanks
What are the advantages and
disadvantages of using LINQ/SQL over
ADO.net?
Linq2sql generates a series of
classes that are 1-to-1 mappings of
your (selected) database tables - this means you don't have to write tedious and error prone data access code
using ado.net yourself.
Linq2sql may not provide enough value for you if you intend on using a custom object-to-relational mapping (non 1-to-1) - of course you could still use linq2sql, but it would mean having an extra layer in between.
Linq2sql allows you to easily query the database using powerful linq expressions. Writing linq queries provides you with intellisense that you wouldn't get if you embedded your queries as strings inside ado.net commands, or wrote stored procs in management studio.
Using linq, you don't need to know t-sql while you will if you use ado.net (although it can definitely an advantage if your linq queries start doing strange things!). An example of this the complexity of writing t-sql queries that provide paging resultsets simply becomes .Skip(page * size).Take(size).
Linq2sql automatically creates t-sql that uses parameterised queries which is much more secure against sql injection attacks than handwritten ado.net code which builds up a query using a string.
Linq2sql doesn't work very well with stored procedures - you are probably better off not bothering with linq2sql if using sprocs.
Linq2sql could require your database tables to be less-tightly locked down than would be possible writing ado.net code using stored procedures.
If it is ADO.net,then what is the best
way to retrieve data means either
calling the stored procedures or
directly calling the t-sql code?
If you'd ruled out linq2sql, and ado.net happened to the better choice for data retrieval, I would be surprised if you were directly calling t-sql code very often or even at all. I would almost certainly expect you to be using stored procedures for reasons that you have queries that are too complex using linq, and/or security requirements.
My question is what is cleanest and most effiecient and professional way of creating DAL for webapplication in asp.net?
In my opinion, the cleanest DAL would probably use linq2sql as it is the lightest and most targeted ORM for SQL Server (assuming your still interested in SQL Server for this specific question of course).
The most efficient could be the handwritten one using ado.net, but this is probably a waste of time as more often than not, you will find a tool such as linq2sql writing better queries than 90% of developers.
In my opinion, the most professional DAL could be linq2sql, but it is more likely to be the Entity Framework of NHibernate (as other answers have suggested) due to more flexibility.
My last choice DAL in terms of cleanliness and professionalism would definitely be a handwritten ado.net one.
The best way to go is O/RM. Small apps Linq2Sql, larger apps Entity Framework 4 or NHibernate (Fluent NHibernate).
Calling SPs from your code means that your app logic is placed somewhere else than in the app code. It's a way to go but at present less and less popular because of TDD.
The best way is to create DAL into a separated logic layer, own assembly.
I would without doubt go for Linq2Sql.
Download Linqpad and play around with the included samples to get started.
You should check out some ORM frameworks, like NHibernate: http://nhibernate.info
If you want efficient data access in terms of performance than there is nothing faster than pure ADO.NET. You chan check it out here: http://ormbattle.net/.

Is there any tool to see the queries run against the database?

Is there any tool that will inspect either asp.net or sql server and report all the queries that are run against the database? The reason I ask is I am using Linq for a project and want to double check what its actually doing for each page.
Ideally I'd like to view a page in a browser and have a report of all the queries that were run to create that page.
I know I can view the SQL it runs for individual queries using debugging/breakpoints, and I know about LinqPad, but I'm afraid Linq is making several more queries on its own to get related data that I may not be directly aware of. Is there anything (tool/program/report/etc) like what I described? Thanks!
EDIT: Is there any FREE tool that can do this? I am using Sql Server 2008 Express and don't have SQL Profiler unfortunately.
Absolutely, There is a SQL tool called SQL Profiler. It does require elevated database permissions in order to run profiler.
There is a decent tutorial on how to run Profiler on TechRepublic.
Another option out there is the NHibernate Profiler. I know that it is not as "free" as SQL Profiler, have never used it, but the screen shots for it look pretty cool.
Profiler is the best tool of them all for this but it can be expensive in inexperienced hands.
You can also try to do "exec sp_who" and then a "dbcc inputbuffer (111)" - just put the process id in the place of 111.
SQL Profiler does that.
Since you are using SQL Server Express, how about this tool?
Profiler for Microsoft SQL Server 2005/2008 Express Edition
Microsoft SQL Server family includes
free Express edition, that is fully
functional, however has some
disappointing limitations which
prevent from using it in development
process. One of them is absense of
profiling tools, standard SQL profiler
is not included. However, now you have
an ability to use express edition for
tuning your system. SQL Server Express
Edition Profiler provides the most of
functionality standard profiler does,
such as choosing events to profile,
setting filters, etc. By now there are
no analogue free tools.
Download Here
A quick and dirty way to log LINQ to SQL queries in ASP.NET is this (assuming a Northwind.Dbml):
NorthwindDataContext context = new NorthwindDataContext();
context.Log = Response.Output;
This will write all queries to the response stream. Nasty, but handy for instant gratification without need for debuggers or profilers etc.
For the LINQ to SQL queries specifically, you can also use the DataContext.Log property to output the queries to a TextWriter, so you can do things like write to debugger output window or (as in my use) to log4net.
These links might help:
Log to debugger output window, file, or memory
Log to log4net
Won't cover the stuff not generated by L2S, so this may not be the end all solution for you... but I've found it helpful.
This one is only free for the first 45 days, but it gives you runtime profiling/logging with a bunch of filter options, SQL Server query execution plan logging etc. Built specifically for profiling L2S apps:
http://www.huagati.com/L2SProfiler

Resources