ctor as place for database call??

  • Thread starter Thread starter hazz
  • Start date Start date
H

hazz

I know it violates alot of design rules but is it possible to have an
ADO.NET database query in a constructor?
As cheesy as that sounds, it may simplify an otherwise very complex design
in a remodel project. thx. -greg
 
Ignoring the architecture implications of what you want to do; Yes it is
possible, a ctor is just as a regular method, executed just after the object
has been created.
 
Thank you for your very timely and practical info Patrik. -greg

Patrik Löwendahl said:
Ignoring the architecture implications of what you want to do; Yes it is
possible, a ctor is just as a regular method, executed just after the object
has been created.

--
Patrik Löwendahl [C# MVP]
www.cshrp.net - "Elegant code by witty programmers"

hazz said:
I know it violates alot of design rules but is it possible to have an
ADO.NET database query in a constructor?
As cheesy as that sounds, it may simplify an otherwise very complex design
in a remodel project. thx. -greg
 
For complexities like you are suggesting, you may also have design issues
that have nothing to do with the constructor.

Yes, you can call ADO in a constructor. The problem comes when you catch
the exceptions. The problem is that most programmers who write
MyObject mobj = new MyObject();
expect that the variable 'mobj' will end up with an object of type MyObject.
If you throw an exception, the variable is unassigned.
You have no other good way to return information to the calling code, to
say: the ADO call, that I didn't tell you was here, failed.

Why not have one object that gets the data, (perhaps encapsulating a
DataRow), and another that takes this object during the constructor to
create your business object. That way, if you have a database error, you
can tell why and you can handle it nicely, without affecting the creation of
your business object.

Something like this:
public MyObject FactoryMyObject(int primarykey)
{
MyDataHolder iholddata = new MyDataHolder(ConnectionManager.instance);
// pass in a singleton that holds the DB connection
try
{
if (iholddata.GetObjectData(primarykey))
return new MyObject(iholddata.ReturnObjectRow());
else
{
// perhaps the db record doesnt exist... let's do something
about it.
}
}
catch (...)
{
// let's catch truly unexpected things, like connection errors
}
return null;
}
 
Back
Top