Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not DbConnection instead of SqlConnection or OracleConnection?

I'm a Java retread pretty new to C#. I'm hoping to stay out of trouble when I crank out a bunch of DML code in the next few weeks.

I'm used to the idea of using JDBC's abstract classes like Connection, Statement, and the like. C# offers similar abstract classes like DbConnection, DbCommand, and so forth, in the System.Data.Common namespace.

But, most of the examples I've seen -- both in MS documentation and other books -- use the concrete classes: SqlConnection, OracleCommand, etc. This kind of concreteness even shows up in the mySQL documentation.

What is the best practice in this area? Is there some strong reason to choose concrete table-server-specific rather than abstract classes for this purpose? (I'm aware of the hazards of downcasting abstract to concrete, of course).

like image 294
O. Jones Avatar asked Mar 12 '11 14:03

O. Jones


2 Answers

The abstract classes were not part of the first versions of the framework, they were introduced in version 2.0. A lot of examples were written before that, or are based on examples that were written before that.

Using concrete or abstract classes is mostly a matter of taste. It's a nice idea to write code that could work with any database, but my experience is that you don't switch database systems very often, and if you do there are so many changes that you need to do that it doesn't matter much if you used abstract classes or not.

like image 89
Guffa Avatar answered Sep 19 '22 20:09

Guffa


Most database-specific ADO.NET classes have extra overloads and/or methods and properties that are specific for that database driver.

Using concrete classes like SqlConnection and OracleConnection makes it easier to access driver-specific features.

like image 37
Philippe Leybaert Avatar answered Sep 22 '22 20:09

Philippe Leybaert