views:

331

answers:

2

Using Subsonic 3.0.0.3 is it feasible to pass a null value to a stored procedures parameter? If so, what is the appropriate way?

Details
Say I have an sp where one of the parameters has a default value like:

 CREATE Procedure Test_SPWithNullParams( @p1 int=null, @p2 varchar(50) ) 
  AS
   SELECT 1 as Stuff

Then in my code I want to do something like:

 var db = new Sandbox.DB();  
 StoredProcedure sproc = db.Test_SPWithNullParams( null , "test");
 //alternately --> db.Test_SPWithNullParams("test");

The way the corresponding function generated in StoredProcedures.cs, however, the parameter for @p1 is not nullable. So what are my alternatives? I came across this article (http://brianmrush.wordpress.com/2010/01/19/subsonic-t4-templates-stored-procedures-nullable-parameters) but it seems like a cumbersome work around that effectively branches the code base.

Alternatively I've thought about manually overriding the command object. Something like:

int dummyInt = -1;
StoredProcedure sproc = db.Test_SPWithNullParams( dummyInt , "test");
sproc.Command.Parameters[0].ParameterValue = DBNull.Value;

Thoughts?

A: 

I don't have Subsonic at hand, but perhaps you could use nullable int.

int? dummyInt = null;
StoredProcedure sproc = db.Test_SPWithNullParams( dummyInt , "test");
Piotr Rodak
Sorry, but defining nullable dummyInt param prevents compilation. Subsonic writes "db.Test_SPWithNullParams" without nullable params. This means I either need to do an (int.hasvalue? int: 0) or define a non-nullable param. Neither allow me to pass a null value to my SP.
EBarr
A: 

No way. Stored procedures are generated only with no nullable types. Why not try something like this?:

StoredProcedure sproc = db.Test_SPWithNullParams( someNullableInt.HasValue ? someNullableInt.Value: 0, "test");
Apocatastasis
I understand that Subsonic generates non-nullable function params. My data model, however, requires nulls in certain situations. The above suggestion sends either a non-null value or a zero rather than the null value I require.
EBarr
Sorry, forgot to ask.. what makes this a "no-way"? My data model requires nulls.
EBarr
You need to modify the Subsonic template StoredProcedures.tt and see if Subsonic core identifies when a procedure have a null parameter. Otherwise you actually need to branch Subsonic.
Apocatastasis