Search code examples
compact-frameworkwindows-cedbconnectiondatabase-connection

SqlConnection DBConnection Windowsce


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


Solution

  • 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