Search

 


Yeah, right!

LINQ to SQL with dynamically generated Stored Prcedure 4

Posted by Paul McConnon Wed, 20 Feb 2008 13:38:00 GMT

I’ve been using LINQ to SQL which is a very nice feature for .NET. It allows you to very quickly model your database objects as objects in code and return them as strongly typed .NET objects.

Seems to have ‘nicked’ (been inspired by?) quite a few ideas from ActiveRecord for Ruby (and Rails). In fact a lot of the new language features (e.g. predicates as anonymous functions for selection, and iterators) seem to borrow from things learnt by being exposed to dynamic languages. All in all it makes .NET much more fun to work in.

Anyway, I was using all this goodness in a project (VS.NET 2008 Orcas beta) and had all my Entities modelled and could use LINQ to query and transform my entities programmatically. I also had a few Stored procedures mapped as methods of the data context. I ran into a problem when I wanted to generate some SQL on the fly so that users could get adhoc filters of their calls.

I didn’t want to drop out into old style ADO.NET using my DBHandler as i would lose the strong typing etc. I decided to use a QueryReport table (as I’ve done numerous times before) to allow me to do ad-hoc queries without being open to SQL Injection. The table consisted of an ID, Name and SQL field. My Stored procedure could take an ID parameter, look up the SQL and use it to filter the calls table

e.g.
ID           Name                SQL
1            All calls           Select * from Calls Where 1 = 1
2            Open calls          Select * from Calls Where Status = 1
3            Old calls           Select * from Calls Where TimeStamp < DateAdd(d, -14,GetDate())
My stored procedure looked like this
ALTER PROCEDURE [dbo].[spExecStoredQuery] 
    @QueryReportID int = 0
AS
BEGIN
    SET NOCOUNT ON;
    declare @queryText varchar(500)
    select 
        @QueryText = SQL 
    from 
        QueryReports
    where
        id = @QueryReportID

    exec (@querytext)
END

The sp always returned All fields from the Calls table, so I should be able to map it to a Call object in the LINQ designer. I created the stored procedure and went about adding it as a method to the LINQ designer.

My problem occurred when I went to set it’s return value to be of type Call. It wouldn’t let me. The option was disabled and greyed out. I immediately assumed that it was because I had an Exec statement in the stored procedure, and assumed it was either a security issue or the designer could not work out it’s return type. I then removed all the exec code from sp and had it return a straight select * from calls.

This still didn’t work. I then renamed the Stored procedure to spStoredQuery. I added it to the designer and I was then able to set its Return Type to Call. This lead me to believe that the designer didn’t like the ‘exec’ in the name of the Stored Procedure. In order to test this I renamed it back to spExecStoredQuery, but, it still worked okay.

I’ve since played around with different versions and names and have discovered the following

  • The first time you add the sp as a method to the designer it checks for return values to try and guess the output type.
  • If it cannot guess the type, it will not let you set a return type in the designer at all
  • If you delete the method then fix the stored procedure so that it returns a constant return type, the designer caches the previous type and will still not let you set a return type.
  • If you rename the stored procedure and re-add it, it checks again, sees a return type (doesn’t matter what it is) This allows you to manually select a return type in the designer.
  • If you then remove the non-dynamic select, and make the stored procedure dynamic, the method still works, and coerces the return type to be of type you selected.

So, the outcome of all this is: If you are dynamically generating a query in a stored procedure and want to add it as a method with a return type in the LINQ designer, add it first with non-dynamic select (select * from foo), override it’s return type if required, then add the dynamic SQL to stored procedure and you’re laughing.


Comments

Leave a response

  1. Avatar
    Jayshree Tue, 15 Apr 2008 10:22:15 GMT
    Is there any way out for above scenario.Because though we add anything in designer.cs of Linq file, the next time when we drag & drop anything on to it,the custom code get removed.Can we change this file dynamically?
  2. Avatar
    Paulie Mon, 21 Apr 2008 08:07:12 GMT
    Jayshree, once you have used the designer to auto-generate the code for the stored procedure, you can move the code out of the .designer.vb or .designer.cs code into your own partial class. In Visual Studio, go to Show All Files, expand the .dbml file, you should see a .layout and a code file. Open the code file and find the code that declares your data context (Partial Public Class FooDataContext) Copy the whole datacontext code into a new code file. In the new code file, remove everything except the stored procedure call declarations, and their return types (ie you don't need Public sub New etc as this is a partial class). This means that when your designer is regenerated, your declaration of your stored procedure remains intact! P
  3. Avatar
    elvedrano Fri, 20 Jun 2008 11:33:53 GMT
    Easy way: You can open the .dbml file with the XML editor and edit the return type there - that is the file from which the .designer.cs code is auto generated from. The .designer.cs file will be automagically generated correctly this way. Hard way: Do not use drag-drop to add your SP to the DBML, instead go to codebehind and add the call manually as a new partial method.
  4. Avatar
    KFrancis Wed, 23 Jul 2008 19:54:32 GMT
    I've tried to do this, but I'm getting "Specified cast is not valid." exceptions when I try to call the stored procedure. This solution fit my issue perfectly until I got those casting exceptions. Any ideas?
Comments