【问题标题】:How to open a password protected SQL Server CE database with Entity Framework如何使用实体框架打开受密码保护的 SQL Server CE 数据库
【发布时间】:2017-04-03 11:01:42
【问题描述】:

我正在使用 EF 6.0 和 SQL Server CE 4.0。 .sdf 文件受密码保护,我通过使用 LinqPad 打开文件进行了验证。当我尝试使用以下连接字符串在代码中打开此数据库时,出现异常:

指定的密码与数据库密码不匹配

代码:

using (var context = new MyDbContext("ExamManagement"))
{
    context.Database.Initialize(false);
}

连接字符串:

<connectionStrings>
    <add name="ExamManagement" 
         connectionString="Data Source=|DataDirectory|Pikeman.sdf;Max Database Size=4091;Password=123;" 
         providerName="System.Data.SqlServerCe.4.0" />
</connectionStrings>

堆栈跟踪:

在 System.Data.Entity.Core.EntityClient.EntityConnection.Open()
在 System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection(Boolean shouldMonitorTransactions)
在 System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectQuery
1.c__DisplayClass7.b__5()
在 System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption)
在 System.Data.Entity.Core.Objects.ObjectQuery1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
at System.Data.Entity.Internal.LazyEnumerator
1.MoveNext()
在 System.Linq.Enumerable.First[TSource](IEnumerable`1 源)

【问题讨论】:

  • 您很可能使用了错误的连接字符串
  • 请看我更新的屏幕截图。似乎连接字符串是正确的,但Password 部分被忽略了。
  • 您是否在 linqpad 中针对正确的数据库文件进行测试?查看您的 bin/debug 文件夹 - 那里可能有 sdf 文件的副本!
  • 连接字符串指向正确的 sdf 文件。如果我从目标目录中删除.sdf,执行上面的代码将在目标目录中创建一个新的.sdf 文件,没有任何异常。但是,新创建的数据库不受密码保护。同样,Password 部分似乎被忽略了。
  • 要查看问题是否与 EF 相关,您能否尝试从生成异常的同一代码位置打开具有相同连接字符串的 ADO.NET 连接。例如context.Database.Connection.Open();new SqlCeConnection("Data Source=|DataDirectory|Pikeman.sdf;Max Database Size=4091;Password=123;").Open(); 让我们知道。

标签: entity-framework sql-server-ce


【解决方案1】:

连接字符串没问题(通常我没有指定最大数据库大小,你可以尝试删除参数但我很确定这不是问题)。
因此,就您而言,我认为您可能正在使用不同的密码打开数据库(如例外情况所示),或者您正在打开错误的数据库。 尝试指定一个绝对路径并从该路径打开数据库,例如

<connectionStrings>
    <add name="ExamManagement" 
         connectionString="Data Source=C:\temp\Pikeman.sdf;Password=123;" 
         providerName="System.Data.SqlServerCe.4.0" />
</connectionStrings>

【讨论】:

  • 好的。发现问题。问题是默认的 DbContext 构造函数使用的默认连接字符串与app.config 文件中的连接字符串不同。当 DbMigrationsConfiguration 为数据库播种时,它使用没有密码的默认连接字符串,这恰好指向与 app.config 连接字符串相同的目录。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-20
  • 2012-06-08
  • 2014-10-02
相关资源
最近更新 更多