Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
What is a way to create SQL Server Compact 3.5 and 4.0 databases in a one application?

The code to create database is simple:
VB
Imports System.Data.SqlServerCe

Friend Function CreateDatabase(ByVal connectionString As String) As Boolean

    Dim engine As SqlCeEngine = Nothing
    Try
        engine = New SqlCeEngine
        engine.LocalConnectionString = connectionString
        engine.CreateDatabase()
        Return True
    Catch ex As SqlCeException
        MsgBox(ex.Message, MsgBoxStyle.Critical)
        Return False
    Finally
        If engine IsNot Nothing Then engine.Dispose()
    End Try

End Function

But it allows creating databases only for one version.
Posted
Comments
joshrduncan2012 5-Dec-13 10:02am    
Why do you want to have Versions 3.5 and 4.0 in the same application?
Sergey Vaselenko 5-Dec-13 10:49am    
Yes. I need have a wizard to create databases of different versions.
joshrduncan2012 5-Dec-13 10:53am    
Why do you want to? I doubt Visual Studio will let you have more than 1 database file of different versions in the same application.
Sergey Vaselenko 5-Dec-13 10:59am    
Our Excel add-in allows working with 3.5 and 4.0. And I want to have the wizard to create both version databases.

1 solution

I've solved the task.

The new function code:
VB
Imports System.Reflection
Imports System.Data.Common

Friend Function CreateDatabase(ByVal factory As DbProviderFactory, ByVal connectionString As String) As Boolean

    Dim asm As Assembly = Assembly.Load(factory.GetType.Assembly.FullName)
    Dim t As Type = asm.GetType("System.Data.SqlServerCe.SqlCeEngine")

    Dim engine = Nothing
    Try
        engine = Activator.CreateInstance(t)
        engine.LocalConnectionString = connectionString
        engine.CreateDatabase()
        Return True
    Catch ex As SystemException
        MsgBox(ex.Message, MsgBoxStyle.Critical)
        Return False
    Finally
        If engine IsNot Nothing Then engine.Dispose()
    End Try

End Function


Usage:
VB
Dim factory As DbProviderFactory
Dim connectionString As String

factory = DbProviderFactories.GetFactory("System.Data.SqlServerCe.4.0")
connectionString = "Data Source=test40.sdf;"

CreateDatabase(factory, connectionString)

factory = DbProviderFactories.GetFactory("System.Data.SqlServerCe.3.5")
connectionString = "Data Source=test35.sdf;"

CreateDatabase(factory, connectionString)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900