1

I'm writing this piece of code in Compact Framework 3.5 under Windows CE 5.0 to handle two different databases:

using System.Data;
using System.Data.SqlClient;
using System.Data.SqlServerCe;
using System.Data.Common;

public myClass
{
    private DbConnection dbCn;
    private DbCommand dbCmd;
    public void myClass(bool ce)
    {
        if (ce)
        {
            dbCn = new SqlCeConnection();
            dbCmd = new SqlCeCommand();
        }
        else
        {
            dbCn = new SqlConnection(); // COMPILER ERROR Cannot implicitly convert type 'System.Data.SqlClient.SqlConnection' to 'System.Data.Common.DbConnection'
            dbCmd = new SqlCommand();// COMPILER ERROR Cannot implicitly convert type 'System.Data.SqlClient.SqlCommand' to 'System.Data.Common.DbCommand'  
        }
    }

Why it cannot convert SqlXX to DbXX ??? from MSDN SqlXX are children of DbXX! Btw, no problem with SqlCeXX. I can not use DbPoviderfactory that is missing from cf.

Thanks

Beorne
  • 189
  • 2
  • 17

1 Answers1

1

What you are trying to do is Covariance and Contravariance in Generics, but that did not come out until .NET 4.0.

[Update] It appears that casting from [DbConnection] to [SqlConnection] could leave out a few parameters, so Microsoft does not allow simple casts.

If you really want to get it done, check out this thread on SO with some good How To code:

C# DbConnection cast to SqlConnection

Community
  • 1
  • 1
  • Sorry I don't understand, SqlConnection inherits from DbConnection, why I can't write: DbConnection dbCn = new SqlConnection() ??????? – Beorne Apr 19 '13 at 13:58
  • Sorry, now I have understood, the problem is the compiler does not know at compile time what is the right object. Some idea to obtain the desidered result (i.e. something like a DbPoviderfactory)? Thanks. – Beorne Apr 19 '13 at 14:05
  • Ok, using interfaces, like IDbConnection. – Beorne Apr 19 '13 at 14:14
  • Sorry. I've been away from the computer. I found a few more details that I posted as an update. –  Apr 19 '13 at 14:39