Enterprise Library Data Access and Stored Procedure Synonyms

The Enterprise Library Data Access application block offers some time-saving routines for calling stored procedures. However, they don't all work when the stored procedure is a synonym.

For example, once I have a Database object, I can get a DataReader from a stored proc called GetUser by simply calling:

C#:
  1. Database db = DatabaseFactory.CreateDatabase();
  2. IDataReader reader = db.ExecuteReader("GetUser", userId);

However, if the stored procedure is a synonym I get an error:

System.InvalidOperationException : The stored procedure 'GetUser' doesn't exist.

The problem isn't actually the Enterprise Library. The problem is - as far as I can see - a bug in ADO.NET. It is the following call that fails:

C#:
  1. SqlCommandBuilder.DeriveParameters((SqlCommand)discoveryCommand);

It seems to me that SqlCommandBuilder.DeriveParameters(SqlCommand command) hasn't been tested with the stored-proc-is-a-synonym scenario: the SQL that it uses to retrieve the parameters returns an empty result set.

I'm not too phased by this problem because I don't really like specifying the parameter values by ordinal position, which is what you're doing when you just supply a params object[] of values. So, I actually prefer using the workaround, which is to create the parameters explicitly:

C#:
  1. Database db = DatabaseFactory.CreateDatabase();
  2. SqlCommand cmd = new SqlCommand("GetUser",
  3.     (SqlConnection)db.CreateConnection());
  4. cmd.CommandType = CommandType.StoredProcedure;
  5. db.AddInParameter(cmd, "@UserId", DbType.Int32, userId);
  6. IDataReader reader = db.ExecuteReader(cmd);

Leave a Reply