Database is being used by another process … but what process?

后端 未结 10 1623

I have written a very small C# program, that uses a very small SQL Server database, purely for some learning & testing purposes. The database is used in this one new pro

10条回答
  •  清酒与你
    2021-01-06 00:48

    Working with VS 2010 and Entity Frameworks using SQL Server I've run into this more than a few times. In my case it happened when I tried to run the program and I had a query open in the Server Explorer. Once it fails I had to drop all the connections to get it to work again.

    VS2010 copies the source database (an .MDF and .LDF file) that you work with in Server Explorer to the projects debug folder. This is the copy you are working with at runtime. When this file is copied is controled by the MDF property Copy to Output Directory by default it is set to Copy always. This means it will try and copy the file on a new build or run and if you have it open elsewhere it fails and then it gets hung up.

    The way to see the connection is to open the SQL Server Management Console. By default VS2010 is using a user instance of SQL Server as specified in the connection string. In the case of Entity Frameworks it is in the App.Config XML.

    The user instance is a separate in memory copy of SQL Server that has all the user rights assigned to the logged in user. To get to it you need to find the proper connection.

    Running this query from the main instance of SQL will show all of the User Instance connections.

    SELECT owning_principal_name, instance_pipe_name, heart_beat FROM sys.dm_os_child_instances
    

    This will return something that looks like this:

       |owning_principle_name | instance_pipe_name                      | heart_beat
    --------------------------------------------------------------------------------
    1  | MyServer\Admin       | \\.\pipe\91B3063E-CD0F-4B\tsql\query\   | dead
    --------------------------------------------------------------------------------
    2  | MyServer\Rich        | \\.\pipe\B04A1D3B-6268-49\tsql\query\   | alive
    

    If you copy the instance name and use it as the server name in a new connection, running as the user associated with it you will see your data from the debug folder.

    Now if you right click on the database and select Tasks > Detach... You will open a Detach Database dialog check the Drop Connections checkbox next to the database file name and click OK.

    The database will be removed from the list and you should be able to build and run you application.

提交回复
热议问题