Kirill
Kirill

Reputation: 459

Get CommandText from DbCommandDefinition

I create a wrapper for System.Data.Common.DbProviderServices class. I need to edit DbCommand.CommandText in this wrapper. How can I get CommandText in CreateDbCommandDefinition method?

Upvotes: 2

Views: 119

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205729

DbCommandDefinition class provides a single CreateCommand method returning DbCommand, hence works like a DbCommand factory.

Assuming you have a DbCommandDefinition instance obtained from the class you wrapping:

DbCommandDefinition commandDefinition = ...;

you can create DbCommand from it and examine all its properties, including the CommandText:

var command = commandDefinition.CreateCommand();
var commandText = command.CommandText;

However you cannot change command properties because every call creates a new command. So you need to create and return a DbCommandDefinition wrapper.

The simplest is like this (works for all DbCommand derived classes that implement ICloneable, which means all "normal" db provider DbCommand implementations, but not for EntityCommand):

class DbCommandDefinitionWrapper : DbCommandDefinition
{
    public DbCommandDefinitionWrapper(DbCommand prototype) : base(prototype) { }
}

and use something like this:

DbCommandDefinition commandDefinition = ...;
var command = commandDefinition.CreateCommand();
command.CommandText = ...;
commandDefinition = new DbCommandDefinitionWrapper(command);

Upvotes: 4

Related Questions