Tutorial :Cannot set OdbcConnection to OdbcCommand.Connection



Question:

On the class level, I have created reference:

System::Data::Odbc::OdbcConnection Connection;

in some method I want to set it to odbcCommand.Connection like this:

::System::Data::Odbc::OdbcCommand Command; Command.Connection=this->Connection;

It reports "cannot convert parameter 1 from 'System::Data::Odbc::OdbcConnection' to 'System::Data::Common::DbConnection ^'"

I dont understand why it speaks about common::DbConnection if the Command.Connection expects OdBcConnection? Thank you


Solution:1

Command.Connection wants a handle (^) to a System::Data::Common::DbConnection

public:  property OdbcConnection^ Connection {      OdbcConnection^ get ();      void set (OdbcConnection^ value);  }  

Instead try to do this:

System::Data::Odbc::OdbcCommand Command;   Command.Connection = %Connection;  

The unary % operator (Tracking reference) returns a CLI tracking references to a CLI object. Tracking references are valid to handles and value types.

Response to comment:

When you create a managed object this way:

OdbcConnection Connection;  

It's a special type of C++/CLI object that are allocated on the stack and that points to the managed object on the managed heap. It isn't a valid managed reference object. To create a managed reference you need to do the following.

OdbcConnection^ Connection; // In the class definition     // In the class constructor do the following:   Connection = gcnew OdbcConnection();  

And DB connection should be deleted in the constructor to guarantee timely clean up. But it is not needed for managed object, they are delete automatically


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »