簡體   English   中英

以編程方式在客戶端計算機上創建SQL Server Compact數據庫

[英]Programmatically create a SQL Server Compact database on the client machines

我最近開始嘗試使用SQL Server Compact和EF6。 我目前正在使用模型第一種方法並從中生成我的類和表。 我很好奇,關於一件事。 如何讓我的程序動態創建數據庫。 當我使用SQL Server Compact / SQLite工具包創建它時,它存在於我的機器上,但是當程序部署到客戶端計算機時,需要創建數據庫。

我想在第一次運行時提示他們一個好的位置,然后創建整個數據庫模式,並在將來使用它。 我查看了這個指南但是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. 為最后一個文件路徑創建設置

在解決方案資源管理器中右鍵單擊您的項目名稱,然后選擇“屬性”。 單擊“設置”選項卡,然后添加新設置,如下所示:

名稱:lastpath
類型:字符串
范圍:用戶
值:

  1. 創建初始屏幕表單(frmSplash)

我看起來像這樣:

啟動畫面

表格上的控件如下:

txtFile
cmdSelectDatabase
cmdNew
cmdOpen
cmdExit

  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設置添加了一個步驟。 如果有什么東西不起作用或者令人困惑的話,請打我,我會盡力幫助你。 祝好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM