以编程方式在客户端计算机上创建SQL Server Compact数据库

时间:2016-09-06 18:36:46

标签: c# .net ado.net sql-server-ce

我最近开始尝试使用SQL Server Compact和EF6。我目前正在使用模型第一种方法并从中生成我的类和表。我很好奇,关于一件事。如何让我的程序动态创建数据库。当我使用SQL Server Compact / SQLite工具包创建它时,它存在于我的机器上,但是当程序部署到客户端计算机时,需要创建数据库。

我想在第一次运行时提示他们找到一个好位置,然后创建整个数据库模式,并在将来使用它。我调查了this guide但是vs开始抱怨它不起作用,因为我没有使用代码优先方法。

如果您需要更多信息,请告诉我们!感谢。

1 个答案:

答案 0 :(得分:2)

我有一个小应用程序我正在使用SQL CE和EF,我在安装应用程序时部署了模板数据库(clickonce)。然后我在应用程序启动时使用spash屏幕加载以前创建的数据库或让用户创建一个新数据库。

当他们创建一个新的数据库时,我只需提示他们找到一个位置,然后将模板数据库复制到所需的位置并使用所需的名称。我还将其设置为使用已部署的数据库,而不给他们机会拥有多个数据库文件。

我们在这里处理几件如下:

  1. SQL CE数据库文件
  2. 我的库存/模板.sdf文件位于我的项目文件夹中,并包含在Visual Studio中的项目中(我正在使用2015)。在解决方案资源管理器中右键单击该文件,然后选择要设置以下内容的属性:

    构建行动 - 内容
    复制到输出目录 - 始终复制

    1. 创建全局变量
    2. 使用现有的模块文件或创建一个如下所示的新文件:

      Public Module Globals
      
        Friend g_recipeData As RecipeEntities
      
      End Module
      
      1. 为最后一个文件路径创建设置
      2. 在解决方案资源管理器中右键单击您的项目名称,然后选择“属性”。单击“设置”选项卡,然后添加新设置,如下所示:

        名称:lastpath
        类型:字符串
        范围:用户
        价值:

        1. 创建初始屏幕表单(frmSplash)
        2. 我的样子如下:

          Splash Screen

          表格上的控件如下:

          txtFile
          cmdSelectDatabase
          cmdNew
          cmdOpen
          cmdExit

          1. 启动画面(frmSplash)代码
          2. 区域“表格方法”

            Private Sub OnFormLoad() Handles Me.Load
            
                txtFile.Text = My.Settings.lastpath
            
                If txtFile.Text <> "" Then
                    cmdOpen.Enabled = True
                    cmdOpen.Select()
                Else
                    cmdNew.Select()
                End If
            
            End Sub
            
            Private Sub FileSelect()
            
                Try
            
                    Dim openFileDialog As New OpenFileDialog()
            
                    openFileDialog.Filter = "sdf files (*.sdf)|*.sdf|All files (*.*)|*.*"
                    openFileDialog.FilterIndex = 1
                    openFileDialog.RestoreDirectory = True
            
                    Dim result As DialogResult = openFileDialog.ShowDialog(Me)
            
                    If result = DialogResult.Cancel Then
                        cmdSelectDatabase.Select()
                        Exit Sub
                    End If
            
                    txtFile.Text = openFileDialog.FileName
            
                    If txtFile.Text <> "" Then
                        cmdOpen.Enabled = True
                        cmdOpen.Select()
                        My.Settings.lastpath = openFileDialog.FileName
                        My.Settings.Save()
                    Else
                        cmdOpen.Enabled = False
                        cmdSelectDatabase.Select()
                    End If
            
                Catch ex As Exception
            
                    MessageBox.Show(ex.Message.ToString, "Application Error")
                    Application.Exit()
            
                Finally
            
                End Try
            
            End Sub 
            
            Private Sub SetConnectionString()
            
                Try
            
                    Dim providerName As String = "System.Data.SqlServerCe.4.0"
                    Dim datasource As String = txtFile.Text
            
                    Dim sqlCeBuilder As New SqlCeConnectionStringBuilder
            
                    sqlCeBuilder.DataSource = datasource
                    sqlCeBuilder.PersistSecurityInfo = True
            
                    g_SQLCeConnectionString = sqlCeBuilder.ConnectionString
            
                    Dim providerString As String = sqlCeBuilder.ToString()
            
                    Dim entityBuilder As New EntityConnectionStringBuilder()
            
                    entityBuilder.Provider = providerName
            
                    entityBuilder.ProviderConnectionString = providerString
            
                    entityBuilder.Metadata = "res://*/RecipeModel.csdl|res://*/RecipeModel.ssdl|res://*/RecipeModel.msl"
            
                    Dim c As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location)
                    Dim section As ConnectionStringsSection = DirectCast(c.GetSection("connectionStrings"), ConnectionStringsSection)
            
                    g_EntityConnectionString = entityBuilder.ConnectionString
            
                    section.ConnectionStrings("RecipeEntities").ConnectionString = g_EntityConnectionString
                    c.Save(ConfigurationSaveMode.Modified)
                    ConfigurationManager.RefreshSection("connectionStrings")
            
                Catch ex As Exception
            
                    MessageBox.Show(ex.Message.ToString, "Application Error")
                    Application.Exit()
                End Try
            
            End Sub 
            
            Private Sub CreateDatabase()
            
                Try
                    Dim saveFileDialog As New SaveFileDialog()
                    saveFileDialog.Filter = "sdf files (*.sdf)|*.sdf"
                    saveFileDialog.Title = "Create Database"
                    saveFileDialog.FilterIndex = 1
            
                    If saveFileDialog.ShowDialog() = DialogResult.OK Then
            
                        File.Copy(Path.Combine(ApplicationDeployment.CurrentDeployment.DataDirectory, "rw.sdf"), saveFileDialog.FileName, True)
            
                        Dim strPathandFile As String = saveFileDialog.FileName
            
                        txtFile.Text = strPathandFile
                        My.Settings.lastpath = strPathandFile
                        My.Settings.Save()
            
                        cmdOpen.Enabled = True
            
                    End If
            
                Catch ex As Exception
            
                    MessageBox.Show(ex.Message.ToString, "Application Error")
                    Application.Exit()
                End Try
            
            End Sub
            
            Private Sub LoadMainApplication()
            
                Try
                    Dim objNewForm As New FrmMain
                    objNewForm.Show()
                    Me.Close()
            
                Catch ex As Exception
            
                    MessageBox.Show(ex.Message.ToString, "Application Error")
                    Application.Exit()
                End Try
            
            End Sub
            

            结束地区

            区域“事件处理程序”

            Private Sub cmdSelectDatabase_Click(sender As Object,
                                                e As EventArgs) Handles cmdSelectDatabase.Click
            
                FileSelect()
                cmdOpen.Select()
            
            End Sub
            
            
            Private Sub cmdCancel_Click(sender As Object, e As EventArgs) Handles cmdExit.Click
                Me.Close()
            End Sub
            
            
            Private Sub cmdOk_Click(sender As Object, e As EventArgs) Handles cmdOpen.Click
            
                Me.Cursor = Cursors.WaitCursor
            
                SetConnectionString()
                LoadMainApplication()
            
                Me.Cursor = Cursors.Default
            
            End Sub
            
            
            Private Sub txtFile_Validated(sender As Object, e As EventArgs) Handles txtFile.Validated
                If txtFile.Text.Length = 0 Then
                    cmdOpen.Enabled = False
                Else
                    cmdOpen.Enabled = True
                End If
            End Sub
            
            Private Sub cmdNew_Click(sender As Object,
                                     e As EventArgs) Handles cmdNew.Click
                CreateDatabase()
                SetConnectionString()
                LoadMainApplication()
            
            End Sub
            
            Private Sub CatchEnterKey(ByVal sender As Object,
                ByVal e As System.Windows.Forms.KeyPressEventArgs) _
                    Handles txtFile.KeyPress, txtPassword.KeyPress
            
            
                If e.KeyChar = ChrW(Keys.Enter) Then
                    cmdOk_Click(sender, e)
                    e.Handled = True
                    Exit Sub
                End If
            
            End Sub
            
            1. 设置全局变量值
            2. 在主应用程序的表单(上面的frmMain)中,将以下内容添加到构造函数中:

              Public Sub New()
              
                  InitializeComponent()
                  g_recipeData = New RecipeEntities
              
              End Sub
              

              如果在模块文件中创建变量时执行上述操作,则设置实体的连接字符串,您无法更改它。您必须首先在app.config中设置连接字符串(使用上面的代码),然后实体将在实例化时使用所需的连接字符串。

              我认为这是现在的基础知识。我强烈建议你在我完成之后再次阅读它。我做了一些更正,甚至为lastpath设置添加了一个步骤。如果有什么东西不起作用或者令人困惑的话,请打我,我会尽力帮助你。祝你好运!