如何在多个应用程序中使用相同的.mdf文件? [英] How to use same .mdf file among multiple applications ?

查看:64
本文介绍了如何在多个应用程序中使用相同的.mdf文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用本地.mdf文件运行的Windows服务,并且还有MVC项目,它们也访问相同的本地.mdf文件。当我同时运行服务和Project时,我收到的错误是Datatbase已被另一个进程使用或出现在UNC Share上。如何使用相同的.mdf文件同时运行这两个应用程序。在这方面的任何帮助都非常感谢。



我尝试过:



我尝试使用事务锁定到数据库但是同样的错误

I have a windows service running using a local .mdf file and also have MVC projects which is also accesing same local .mdf file. When i run both the service and Project simultaneously i am getting error that "Datatbase is already used by another process or present on UNC Share". How do i run both both applications simultaneously using same .mdf file. Any help in this regard is highly appreciated.

What I have tried:

I have tried using transactions locks on to the database yet same error

推荐答案

如果你通过OleDbConnection对象直接连接到MDF文件,那么MDF的问题文件是当您打开与它们的连接时,它们对文件进行独占锁定以便可以将其写入 - 这意味着在您释放连接之前,没有其他应用程序可以连接到该文件。如果他们尝试,他们将收到您遇到的错误消息。



您有两种选择:

1)更改所有应用程序以打开连接,完成工作,并尽快关闭连接,同时暂停和重试连接失败。

2)更改所有应用程序以使用SQL Server(或MySql)而不是直接连接到MDF文件,并让它处理多次访问(这就是它的用途!)



第二个听起来像很多工作,但它实际上更简单比第一个,并消除了许多问题,多次访问MDF文件给你尚未遇到。差不多,这是用SqlConnection,SqlCommand等替换OleDbConnection,OleDbCommand等对象的情况。



如果你已经在使用SQL Server,那么问题可能是你的连接字符串:你的应用程序都不应该附加数据库 - 它应该由Sql Server永久保存和处理。附加是一种特殊的Express版本模式,仅用于调试,不应在实时代码中使用。
If you are connecting directly to MDF Files via OleDbConnection objects, then the problem with MDF files is that when you open a connection to them, they take an exclusive lock on the file so that it can be written to - which means that no other application can connect to the file until you release the connection. If they try, they will get the error message you have experienced.

You have two choices:
1) Change all applications to open the connection, do the work, and close the connection as fast as possible, while pausing and retrying if the connection fails.
2) Change all applications to use SQL Server (or MySql) instead of direct connection to MDF files, and let it handle the multiple accesses (that is what it is there for!)

The second sounds like a lot of work, but it's actually simpler than the first, and eliminates a lot of the problems that multiple access to MDF files gives that you haven't met yet. Pretty much, it's a case of replacing OleDbConnection, OleDbCommand, and such like objects with SqlConnection, SqlCommand, and so on.

If you are already using SQL Server, then the problem is probably your connections string: none of your apps should be attaching the database - it should be permanently held and processed by Sql Server. Attaching is a special Express edition mode for debugging only, and should not be used in "live" code.


这篇关于如何在多个应用程序中使用相同的.mdf文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆