views:

173

answers:

2

I am using Enterprise Library 4.1.

While I am executing the code by using :

using ( _db = DatabaseFactory.CreateDatabase("NLayerDB") )

{

DbCommand dbCommand = _db.GetStoredProcCommand("someSPName");

_db.AddInParameter(dbCommand, "Id", DbType.Int32, id);

result= _db.ExecuteNonQuery(dbCommand);

}

I am receiving the following error :

Microsoft.Practices.EnterpriseLibrary.Data.Database type used in a using statement must be implicitly convertible to 'System.IDisposable'

What is the exact problem of having USING statement here ?

+1  A: 

You're not gaining anything by actually having the using (and as you've noted, it won't actually compile).

Wrapping your object-creation code "using" statements ensure that the object you created is disposed when the "using" block exits. It only makes sense for object that implement IDisposable, because other types can't be explicitly disposed.

You can safely remove your using block and end up with this:

_db = DatabaseFactory.CreateDatabase("NLayerDB");
DbCommand dbCommand = _db.GetStoredProcCommand("someSPName"); 
_db.AddInParameter(dbCommand, "Id", DbType.Int32, id); 
result = _db.ExecuteNonQuery(dbCommand);

If DbCommand implements IDisposable (I'm not sure, having never used EntLib's DAAB) then you may want to wrap just that part of the code in a using block:

_db = DatabaseFactory.CreateDatabase("NLayerDB");
using (DbCommand dbCommand = _db.GetStoredProcCommand("someSPName"))
{
    _db.AddInParameter(dbCommand, "Id", DbType.Int32, id); 
    result = _db.ExecuteNonQuery(dbCommand); 
}
Matt Hamilton
+1  A: 

Microsoft.Practices.EnterpriseLibrary.Data.Database does not implement IDisposable, which is a requirement for the using statement.

The DbCommand object does implement IDisposable so it might be more appropriate to use that in the using statement instead.

Zach Bonham
oh! I am wondering...Then how the Garbage collection works for EntLib Database?
Garbage collection will work on Database just like any other managed object. When its no longer in use it will be collected during normal GC processing. I can't tell from your snippet where _db is declared. By the variable name, I would assume at a class level. If that is so, then _db should be collected sometime after the class its declared in is no longer being referenced.DbCommand is the object you want to be focused on releasing as soon as possible when you no longer need it, so the "using" statement is definitely appropriate for it.
Zach Bonham