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

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

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

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

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

最佳答案

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

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

我们这里处理的部分如下:

  1. SQL CE数据库文件

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

构建操作 - 内容
复制到输出目录 - 始终复制

  1. 创建全局变量

要么使用现有的模块文件,要么创建一个如下所示的新文件:

Public Module Globals

  Friend g_recipeData As RecipeEntities

End Module
  1. 为最后一个文件路径创 build 置

在解决方案资源管理器中右键单击您的项目名称并选择“属性”。单击“设置”选项卡并添加一个新设置,如下所示:

名称:最后路径
类型:字符串
范围:用户
值:

  1. 创建闪屏表单 (frmSplash)

我的看起来像这样:

Splash Screen

窗体上的控件如下:

txt文件
命令选择数据库
命令新建
命令打开
命令退出

  1. 启动画面 (frmSplash) 代码

区域“表单方法”

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. 设置全局变量值

在主应用程序(上面的 frmMain)的窗体上,将以下内容添加到构造函数中:

Public Sub New()

    InitializeComponent()
    g_recipeData = New RecipeEntities

End Sub

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

我认为这是目前的基础。既然我已经完成了,我强烈建议您再次阅读它。我做了一些更正,甚至为 lastpath 设置添加了一个步骤。如果出现问题或令人困惑,请联系我,我会尽力提供帮助。祝你好运!

关于c# - 以编程方式在客户端计算机上创建 SQL Server Compact 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39355724/

相关文章:

model-view-controller - ADO.NET 实体 - 模型优先数据注释

c# - 多次读取 IDataReader 时出错

javascript - 在 http Post 中传递对象数组

c# - +ffff 在此 DateTime 格式中代表什么 ddd, d MMM yyyy HH :mm:ss +ffff

css - 为什么深灰色比灰色浅?

.net - 触发 Azure Web 作业失败时获取通知

Oracle db 给出 ORA-01722 似乎没有任何原因

c# - Excel 插件连接到 REST API

c# - Silverlight 4 可以与本地主机建立 TCP 连接吗?

c# - 映射路径 '/' 失败。 .net 4.0