SubSonic – Custom Query

SubSonic – how to execute custom query using QueryCommand and read a value from single row:

string result = String.Empty;
int id = 1;
string sqlCommand = "select Col1 from Table1 where id = @IdParam";

QueryCommand cmd = new QueryCommand(sqlCommand);

// Remember to set provider name in case if multiple databases are being
// used in the current project
// (because DataService remembers the latest executed connection string)!
cmd.ProviderName = DBTable1.Schema.Provider.Name;

cmd.AddParameter("@IdParam", id, DbType.Int32);

using (IDataReader rdr = DataService.GetReader(cmd))
    if (rdr.Read())
        result = Convert.ToString(rdr[rdr.GetOrdinal("Col1")]);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: