EntityFramework.dll 中发生 System.Data.DataException 错误
Posted
技术标签:
【中文标题】EntityFramework.dll 中发生 System.Data.DataException 错误【英文标题】:System.Data.DataException error occurred in EntityFramework.dll 【发布时间】:2014-04-29 09:47:39 【问题描述】:我一直在关注这个教程Getting Started with Entity Framework 6 Code First using MVC 5。
当我到达需要运行程序的部分并单击 Student 以便程序创建数据库时,我收到以下错误。
System.Data.DataException 未被用户代码处理 H结果=-2146233087 消息=初始化数据库时发生异常。有关详细信息,请参阅 InnerException。 来源=实体框架 堆栈跟踪: 在 System.Data.Entity.Internal.InternalContext.PerformInitializationAction(动作动作) 在 System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() 在 System.Data.Entity.Internal.LazyInternalContext.b__4(InternalContext c) 在 System.Data.Entity.Internal.RetryAction
1.PerformAction(TInput input) at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action
1 操作) 在 System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase() 在 System.Data.Entity.Internal.InternalContext.Initialize() 在 System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(类型 entityType) 在 System.Data.Entity.Internal.Linq.InternalSet1.Initialize() at System.Data.Entity.Internal.Linq.InternalSet
1.GetEnumerator() 在 System.Data.Entity.Infrastructure.DbQuery1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() at System.Collections.Generic.List
1..ctor(IEnumerable1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable
1 源) 在 c:\Users\Office\Documents\Visual Studio 2013\Projects\ContosoUniversityFollow\ContosoUniversityFollow\Controllers\StudentController.cs:line 21 中的 ContosoUniversityFollow.Controllers.StudentController.Index() 在 lambda_method(闭包,ControllerBase,对象 []) 在 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase 控制器,Object[] 参数) 在 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext 控制器上下文,IDictionary2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary
2 参数) 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod() 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.b__36(IAsyncResult asyncResult,ActionInvocation innerInvokeState) 在 System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase
1.End() 在 System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult,对象标记) 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3c() 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.c__DisplayClass45.b__3e() 内部异常:System.Data.Entity.Core.EntityException H结果=-2146233087 消息=底层提供程序在打开时失败。 来源=实体框架 堆栈跟踪: 在 System.Data.Entity.Core.EntityClient.EntityConnection.Open() 在 System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection() 在 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__DisplayClassb.b__9() 在 System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation) at System.Data.Entity.Core.Objects.ObjectQuery
1.GetResults(Nullable1 forMergeOption) at System.Data.Entity.Core.Objects.ObjectQuery
1..GetEnumerator>b__0() 在 System.Lazy1.CreateValue() at System.Lazy
1.LazyInitValue() 在 System.Lazy1.get_Value() at System.Data.Entity.Internal.LazyEnumerator
1.MoveNext() 在 System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source) at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__1[TResult](IEnumerable
1 序列) 在 System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable1 query, Expression queryRoot) at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression) at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression) at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable
1 源) 在 System.Data.Entity.Internal.EdmMetadataRepository.QueryForModelHash(Func2 createContext) at System.Data.Entity.Internal.InternalContext.QueryForModelHash() at System.Data.Entity.Internal.ModelCompatibilityChecker.CompatibleWithModel(InternalContext internalContext, ModelHashCalculator modelHashCalculator, Boolean throwIfNoMetadata) at System.Data.Entity.Internal.InternalContext.CompatibleWithModel(Boolean throwIfNoMetadata) at System.Data.Entity.Database.CompatibleWithModel(Boolean throwIfNoMetadata) at System.Data.Entity.DropCreateDatabaseIfModelChanges
1.InitializeDatabase(TContext 上下文) 在 System.Data.Entity.Internal.InternalContext.c__DisplayClasse1.<CreateInitializationAction>b__d() at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) InnerException: System.Data.SqlClient.SqlException HResult=-2146232060 Message=Cannot open database "ContosoUniversity1" requested by the login. The login failed. Login failed for user 'Office-PC\Office'. Source=.Net SqlClient Data Provider ErrorCode=-2146232060 Class=11 LineNumber=65536 Number=4060 Procedure="" Server=(LocalDb)\v11.0 State=1 StackTrace: at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource
1 重试,DbConnectionOptions userOptions,DbConnectionInternal& 连接) 在 System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection,TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource
1 重试,DbConnectionOptions userOptions) 在 System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection,DbConnectionFactory connectionFactory,TaskCompletionSource1 retry, DbConnectionOptions userOptions) at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource
1 重试) 在 System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry) at System.Data.SqlClient.SqlConnection.Open() at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0() at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func
1 操作) 在 System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(操作操作) 在 System.Data.Entity.Core.EntityClient.EntityConnection.Open() 内部异常:
我很难解决这个问题。我遵循一切,甚至重做只是为了确保我做对了。我不认为我错过任何步骤。但是有一点不对劲。如果我运行整个示例代码,一切正常。
感谢任何帮助。
谢谢,
堆
编辑:
对于一个简单的事情导致这样的错误真是令人沮丧。 @mmeasor,我也刚刚看到了那个错误。它无法连接到数据库。所以这导致我检查连接。
发生的事情是,起初我使用了这个连接字符串:
因此 EntityFramework 在此处创建了一个数据库文件 ContosoUniversity1.mdf,例如 C:\Users\Office\ContosoUniversity1.mdf。但后来我希望它创建另一个并使用它,这次我希望它位于程序 App_Data\ 文件夹中。
所以我将 web.config 文件修改为:
我想如果我这样做,EF 将在 \App_Data\ 文件夹中为我创建一个新数据库并链接到该数据库,而不是 C:\Users\Office 中的旧数据库。
我错了!那是我开始收到上面发布的错误的时候。而且我找不到导致问题的原因。
使用第二个 web.config,我尝试将数据库文件复制到 App_Data 文件夹,但这仍然不起作用。
现在我使用第一个连接字符串,它工作正常。
所以现在的问题是:如何让程序链接到 \App_Data\ 文件夹中的数据库文件?
谢谢,
堆
【问题讨论】:
你看内部异常了吗?它说 Office-PC\Office 登录失败。确保用户有权访问数据库,并且您拥有正确的密码 【参考方案1】:我在尝试将 Conosto 大学教程数据库的位置从用户文件夹更改为 App_Data 文件夹时遇到了同样的问题。 John Locke 让我想到这可能与必须更改数据库名称有关。
稍微更改 web.config 文件中命名的数据库的名称(这工作不一致,但工作始终不一致。如果我不得不再次测试这个......我相信我会在某个时候......我将远离重用名称 - 即不要在两个名称首选项之间来回切换(例如 database1 和 database2 回到 database1 - 我会使用完全新颖的名称,例如 databse7...database8...database9 - 从以前获取名称用过的名字)
我也很幸运,一旦使用我不想要的名称创建了数据库,将数据库名称更改为我想要的名称并在 web.config 中匹配该名称(即我能够创建一个“ database3.mdf" 文件成功,然后在操作系统中将其更改为我想要的 - "database1.mdf" 并将 web.config 文件与 database1 匹配,并在第一次尝试时连接)
【讨论】:
“更改数据库名称”就像一个冠军。我的场景是我一直在通过一些 o365 实验室工作,其中有一个创建数据上下文的类。在我第二次通过实验室时,它无法创建数据库,即使它要去本地 App_Data。将数据库名称更改为唯一可解决此问题。我正在做的实验室是github.com/OfficeDev/TrainingContent/blob/master/O3651/…【参考方案2】:我有这个问题好几天了(“EntityFramework.dll 中发生了‘System.Data.DataException’类型的异常,但没有在用户代码中处理”),自从将连接字符串更改为许多不同的方法后,我尝试了所有方法在网上看到问答, 我的解决方案?... 用另一个名字创建了一个新项目,它救了我。
【讨论】:
【参考方案3】:这里 EmployeeDetail 是一个表名,Employee 是一个模型名。和 ID、Branch、Salary 和 UID 是表字段:
public ActionResult Index()
List<EmployeeDetail> employees = context.EmployeeDetails.ToList();
List<Employee> emp = new List<Employee>();
foreach(EmployeeDetail item in employees)
emp.Add(new Employee
ID=Convert.ToInt32(item.ID),
Branch=item.Branch,`enter code here`
Salary=Conve`enter code here`rt.ToInt32(item.Salary),
UID = Convert.ToInt32(item.ID),
);
return View(emp);
查看页面代码
<div style="font-family:Arial">
<h2>Index</h2>
<ul>
@foreach (var emp in Model)
<li>
@html.ActionLink(emp.Branch, "Details", new id = emp.ID );
</li>
</ul>
</div>
【讨论】:
请详细说明这段代码是如何回答这个问题的。以上是关于EntityFramework.dll 中发生 System.Data.DataException 错误的主要内容,如果未能解决你的问题,请参考以下文章
EntityFramework.dll 中出现“System.Data.Entity.Core.MappingException”类型的异常,但未在用户代码中处理