多个用户访问网络共享上的 SQL Compact 数据库.sdf 文件is not supported。为此,您应该使用 SQL Server Express 版本。 在 stackoverflow 上也有多个关于此主题的帖子。 3.5 版支持专门从网络共享打开 .sdf 文件,但 4.0 版不支持。但是没有 SQL CE 版本支持多个网络用户对 1 个 .sdf 文件的共享访问。
但是升级您的应用程序以同时支持 SQL Express 和 SQL Compact 数据库可能是相对容易的任务。这取决于您的应用程序如何访问数据。例如,使用实体框架可以根据您的实际数据库连接生成查询。
您还可以使用通用类 DbConnection、DbCommand 等来代替 SqlCeConnection、SqlCeCommand 等 - 因此您可以更改使用的数据库类型,而无需维护项目的两个单独版本。
下载SQL Express 2014 with Tools SQLEXPRWT http://msdn.microsoft.com/cs-cz/evalcenter/dn434042.aspx。 (您最终也可以使用旧版本,例如 2008)SQL Server 具有比 SQL CE 更多的 SQL 功能和数据类型,因此请注意只使用与 SQL CE 兼容的东西。
在你的 app.config 中有两个连接字符串:
<add name="CompactDBConnection" connectionString="data source=|DataDirectory|\CE.sdf; password=xxxxxx; SSCE:Max Buffer Size=16384; temp file max size=256; ssce:autoshrink threshold=100; ssce:max database size=4091" providerName="System.Data.SqlServerCe.4.0" />
<add name="ExpressDBConnection" connectionString="Server=myServerName\myInstanceName;Database=myDataBase;User Id=myUsername; Password=myPassword;" providerName="System.Data.SqlClient" />
然后您可以选择在应用启动时使用哪一个
要创建 DbConnection,请检查此C# Retrieving correct DbConnection object by connection string。
这是一个使用DbCommand而不是SqlCeCommand调用存储过程的小例子:
DbConnection dbConn = GetConnection(connStr);
DbProviderFactory sqlF = DbProviderFactories.GetFactory(dbConn);
using (DbCommand b2bcmd = sqlF.CreateCommand())
{
DbParameter msg = sqlF.CreateParameter();
msg.ParameterName = "@errorMessage";
msg.Direction = ParameterDirection.Output;
msg.DbType = DbType.String;
msg.Value = string.Empty;
msg.Size = 2048;
b2bcmd.Connection = dbConn;
b2bcmd.CommandType = CommandType.StoredProcedure;
b2bcmd.CommandText = "PB2BImport";
b2bcmd.Parameters.Add(msg);
b2bcmd.ExecuteNonQuery();
result = Convert.IsDBNull(msg.Value) ? "N/A" : (string)msg.Value;
}
我假设您不使用实体框架 - 但使用它会更容易。