问题描述:

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.

网友答案:

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:

USE master 
GO 
ALTER DATABASE YourDatabaseName 
SET OFFLINE WITH ROLLBACK IMMEDIATE 
GO 

(from this answer)

网友答案:

You need to stop the SQL server or take the database offline before copying the files.

相关阅读:
Top