Enterprise Library 2 - ExecuteNonQuery: Connection property has not been initialized

October 16, 2007 07:48 by digitalman
Ok, this has bitten me twice now.

The following code uses the Microsoft Patterns & Practices Enterprise Library 2.0 Data Access Layer. The _db variable is already instantiated and working for simple select queries. Here I want to add an entry with parameters. This is using straight SQL text but could also be using a stored procedure.

DbCommand cmd = _db.GetSqlStringCommand("INSERT INTO SomeTable VALUES (@Name, @Description)");
_db.AddInParameter(cmd, "@Name", DbType.String, "Test");
_db.AddInParameter(cmd, "@Description", DbType.String, "My Test");
cmd.ExecuteNonQuery();
This looks fairly straight forward. However you will get the error, "ExecuteNonQuery: Connection property has not been initialized" if you run it. It turns out calling the command object's ExecuteNoQuery method does not automatically get the Database object connection applied to it. The proper way to write this is:

_db.ExecuteNonQuery(cmd);

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts