1

I am writing an app that I want the user to choose a SQL Server CE or SQL Server Express database as the background. However these use separate references, and separate methods.

Is there a proper .NET method of doing this, or do I store a user preference and use if then statements throughout the whole program checking the database type such as:

if (Properties.Settings.Default.dbType == 1)
{ SqlConnection blah = new SqlConnection}
else if (Properties.Settings.Default.dbType == 2)
{ SqlCEConnection blah = new SqlCEConnection}

This works, it just seems there should be a better way.

1 Answer 1

2

Both SqlConnection and SqlCEConnection extend System.Data.Common.DbConnection, so declare "blah" as DbConnection, and you will able to use the same methods and properties.

To actually create the correct connection type, use the System.Data.Common.DbProviderFactories and System.Data.Common.DbProviderFactory classes. For example:

DbProviderFactory providerFactory = DbProviderFactories.GetFactory("The Provider Name");

using (DbConnection connection = providerFactory.CreateConnection())
{
    connection.ConnectionString = "The Connection String";

    connection.Open();

    // Use the "connection" object here
}

For "The Provider Name", you would put in either "System.Data.SqlClient" or "System.Data.SqlServerCe" depending on the database type. And then for "The Connection String", you would put in the correct connection string for the provider type.

EDIT: this technique works well with your App.config file and the System.Configuration.ConfigurationManager class. For example, if your App.config file looks like this:

<?xml version="1.0" encoding="utf-8"?>

<configuration>
    <connectionStrings>
        <add name="TheConnectionString" providerName="System.Data.SqlClient" connectionString="Blah Blah Blah" />
    </connectionStrings>
</configuration>

Then you can access these configuration settings like this:

DbProviderFactory providerFactory = DbProviderFactories.GetFactory(ConfigurationManager.ConnectionStrings["TheConnectionString"].ProviderName);

using (DbConnection connection = providerFactory.CreateConnection())
{
    connection.ConnectionString = ConfigurationManager.ConnectionStrings["TheConnectionString"].ConnectionString;

    connection.Open();

    // Use the "connection" object here
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.