在 C# 中运行时用备份文件替换数据库 MDF 文件
我使用 Linq to Sql 编写了相当长的 C# 程序,并且我的数据存储在位于程序 EXE 附近的 MDF 文件中。 我的程序的一部分有一个表单,只需将 MDF 和 LDF 文件复制到用户指定的文件夹中即可备份数据库文件。
但是,如果我查询数据库,然后尝试用备份替换原始文件,我将得到文件在另一个进程中打开异常如预期! 问题是我不知道如何关闭SqlServer实例中的MDF文件。
我对 Linq to Sql 还很陌生,我让 Visual Studio 的向导来处理大部分工作!因此,如果我想做的事情听起来很愚蠢,我提前表示抱歉! :D
非常感谢任何有关我的案例的更好编程方法的帮助或建议。
I've written quite a long C# program using Linq to Sql and my data are stored in an MDF file located near my program's EXE.
A part of my program has a form for backing up the database files simply by copying the MDF and LDF files into a user-specified folder.
However if I query the database and then try to replace the original files with the backups, I'll get the file open in another process exception as expected!
The problem is that I don't know how to close the MDF file in the SqlServer instance.
I'm pretty new to Linq to Sql and I let the Visual Studio's wizards to handle most of the job! So I'm sorry in advance if anything I'm trying to do sounds stupid! :D
Any help or suggestion for better programming methods for my case is greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可能无法满足您的需求,但您可能需要考虑将应用程序切换为使用 Sql Server Compact Edition(“SqlCE”)而不是 Sql Server(适当的)。听起来您使用数据库本质上是应用程序的后备文件,这并不是 Sql Server 的真正预期目的。 SqlCE 是专门为此类事情而设计的,并且在桌面上运行得很好。您可以轻松地关闭与 SqlCE 的连接并像操作任何其他文件一样操作 SDF 文件(您尝试对 Sql Server MDF 文件执行的操作,但未成功)。
更新:这看起来像您需要的:(
来自这个答案)
This may not work for your needs, but you might want to consider switching your application to use Sql Server Compact Edition ("SqlCE") instead of Sql Server (proper). It sounds like you're using the database as essentially a backing file for your application, which isn't really the intended purpose of Sql Server. SqlCE is designed specifically for this kind of thing, and works great on the desktop. You can easily close your connection to SqlCE and manipulate the SDF file like any other file (what you're trying to do with the Sql Server MDF file, unsuccessfully).
Update: This looks like what you need:
(from this answer)
在复制文件之前,您需要停止 SQL Server 或使数据库脱机。
You need to stop the SQL server or take the database offline before copying the files.