How to view LINQ Generated SQL statements?

It’s multiple options how we can view generated SQL from LINQ to SQL or Entity framework. My favorite is by SQL Server profiler. BUT sometimes I need something quicker. And here is the option how to look directly at the DB (SQL Server) to the last executed query:

SELECT TOP 5 
	deqs.last_execution_time AS [Time], 
	dest.text AS [Query]
FROM 
	sys.dm_exec_query_stats AS deqs
	CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE 
	dest.text like '%vw_Visitor%'
ORDER BY 
	deqs.last_execution_time DESC

Only one note: Beneficial can by the WHERE condition … I suppose that the query looking under particular Table or View or SP so I can help to SQL server by adding WHERE condition like dest.text like '%vw_Visitor%' = By this I said something like : hey server, give me only query where is mentioned something related with particular View called vw_Visitor.  

InsertOnSubmit throwing NullReferenceException

Be careful when you are using your own constructor in partial classes on entities generated for LINQ to SQL (Data context entities). When you create your own constructor is really important to call the default constructor in it. Example :

Default contructor on LINQ to SQL entities in partial class


Why? Because is important to execute the default generated constructor while execution of your program. This constructor contains some Initialization under your entity:

Generated contructor of LINQ to SQL object
Otherwise you will getting following error:

[NullReferenceException: Object reference not set to an instance of an object.]
   System.Data.Linq.Mapping.EntitySetDefSourceAccessor`2.GetValue(T instance) +18
   System.Data.Linq.Mapping.MetaAccessor`2.GetBoxedValue(Object instance) +56
   System.Data.Linq.StandardTrackedObject.HasDeferredLoader(MetaDataMember deferredMember) +128
   System.Data.Linq.StandardTrackedObject.get_HasDeferredLoaders() +130
   System.Data.Linq.StandardChangeTracker.Track(MetaType mt, Object obj, Dictionary`2 visited, Boolean recurse, Int32 level) +269
   System.Data.Linq.StandardChangeTracker.Track(Object obj, Boolean recurse) +113
   System.Data.Linq.Table`1.InsertOnSubmit(TEntity entity) +383