以编程方式在客户端计算机上创建 SQL Server Compact 数据库
Programmatically create a SQL Server Compact database on the client machines
我最近开始试验 SQL Server Compact 和 EF6。我目前正在使用模型优先方法并从中生成我的 类 和表格。不过我很好奇,有一件事。我怎样才能让我的程序动态创建数据库。它存在于我的机器上,因为我使用 SQL 服务器 Compact/SQLite 工具包创建它,但是当程序部署到客户端计算机时,需要创建数据库。
我想先 运行 提示他们找到一个好的位置,然后创建整个数据库架构,并在将来使用它。我调查了 this guide 但 vs 开始抱怨它不起作用,因为我没有使用代码优先方法。
如果您需要更多信息,请告诉我!谢谢
我有一个正在使用 SQL CE 和 EF 开发的小应用程序,我会在安装该应用程序时部署模板数据库 (clickonce)。然后我在应用程序启动时使用 spash 屏幕加载以前创建的数据库或让用户创建一个新数据库。
当他们创建一个新的数据库时,我只是提示他们输入一个位置,然后使用他们想要的名称将模板数据库复制到他们想要的位置。我还将其设置为使用已部署的数据库,而不给他们机会拥有多个数据库文件。
我们这里处理的几件如下:
- SQL CE 数据库文件
我的 stock/template .sdf 文件位于我的项目文件夹中,并包含在 Visual Studio 的项目中(我使用的是 2015)。右键单击解决方案资源管理器中的文件,然后 select 设置以下属性:
构建操作 - 内容
复制到输出目录 - 始终复制
- 创建全局变量
要么使用现有的模块文件,要么创建一个如下所示的新文件:
Public Module Globals
Friend g_recipeData As RecipeEntities
End Module
- 为最后一个文件路径创建设置
在解决方案资源管理器中右键单击您的项目名称并选择“属性”。单击“设置”选项卡并添加如下新设置:
名称:上次路径
类型:字符串
范围:用户
值:
- 创建闪屏窗体 (frmSplash)
我的看起来像这样:
窗体上的控件如下:
txt文件
cmdSelectDatabase
cmdNew
cmd打开
命令退出
- 启动画面 (frmSplash) 代码
区域"Form Methods"
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
结束区域
地区"Event Handlers"
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
- 设置全局变量值
在主应用程序(上面的 frmMain)的窗体上,将以下内容添加到构造函数中:
Public Sub New()
InitializeComponent()
g_recipeData = New RecipeEntities
End Sub
如果在模块文件中创建变量时执行上述操作,则实体的连接字符串已设置且无法更改。您必须先在 app.config 中设置连接字符串(使用上面的代码),然后实体将在实例化时使用所需的连接字符串。
我认为这是目前的基础知识。既然我已经完成了,我强烈建议您再次阅读它。我做了一些更正,甚至为 lastpath 设置添加了一个步骤。如果出现问题或令人困惑,请联系我,我会尽力提供帮助。祝你好运!
我最近开始试验 SQL Server Compact 和 EF6。我目前正在使用模型优先方法并从中生成我的 类 和表格。不过我很好奇,有一件事。我怎样才能让我的程序动态创建数据库。它存在于我的机器上,因为我使用 SQL 服务器 Compact/SQLite 工具包创建它,但是当程序部署到客户端计算机时,需要创建数据库。
我想先 运行 提示他们找到一个好的位置,然后创建整个数据库架构,并在将来使用它。我调查了 this guide 但 vs 开始抱怨它不起作用,因为我没有使用代码优先方法。
如果您需要更多信息,请告诉我!谢谢
我有一个正在使用 SQL CE 和 EF 开发的小应用程序,我会在安装该应用程序时部署模板数据库 (clickonce)。然后我在应用程序启动时使用 spash 屏幕加载以前创建的数据库或让用户创建一个新数据库。
当他们创建一个新的数据库时,我只是提示他们输入一个位置,然后使用他们想要的名称将模板数据库复制到他们想要的位置。我还将其设置为使用已部署的数据库,而不给他们机会拥有多个数据库文件。
我们这里处理的几件如下:
- SQL CE 数据库文件
我的 stock/template .sdf 文件位于我的项目文件夹中,并包含在 Visual Studio 的项目中(我使用的是 2015)。右键单击解决方案资源管理器中的文件,然后 select 设置以下属性:
构建操作 - 内容
复制到输出目录 - 始终复制
- 创建全局变量
要么使用现有的模块文件,要么创建一个如下所示的新文件:
Public Module Globals
Friend g_recipeData As RecipeEntities
End Module
- 为最后一个文件路径创建设置
在解决方案资源管理器中右键单击您的项目名称并选择“属性”。单击“设置”选项卡并添加如下新设置:
名称:上次路径
类型:字符串
范围:用户
值:
- 创建闪屏窗体 (frmSplash)
我的看起来像这样:
窗体上的控件如下:
txt文件
cmdSelectDatabase
cmdNew
cmd打开
命令退出
- 启动画面 (frmSplash) 代码
区域"Form Methods"
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
结束区域
地区"Event Handlers"
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
- 设置全局变量值
在主应用程序(上面的 frmMain)的窗体上,将以下内容添加到构造函数中:
Public Sub New()
InitializeComponent()
g_recipeData = New RecipeEntities
End Sub
如果在模块文件中创建变量时执行上述操作,则实体的连接字符串已设置且无法更改。您必须先在 app.config 中设置连接字符串(使用上面的代码),然后实体将在实例化时使用所需的连接字符串。
我认为这是目前的基础知识。既然我已经完成了,我强烈建议您再次阅读它。我做了一些更正,甚至为 lastpath 设置添加了一个步骤。如果出现问题或令人困惑,请联系我,我会尽力提供帮助。祝你好运!