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

有帮助吗?

解决方案

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top