MVC连接错误:基础提供程序在Open上失败

时间:2015-04-15 10:37:10

标签: c# asp.net asp.net-mvc entity-framework asp.net-mvc-4

我是ASP.NET MVC4的新手。我正在尝试使用实体框架连接数据库,但没有成功。
连接字符串如下

<add name="EmployeeContext" connectionString="Data Source=192.168.1.101;Initial Catalog=MVCPrac;User ID=sa;Password=anything"  providerName="System.Data.SqlClient"/>

我使用以下代码获取数据:

public ActionResult Details(int id)
    {
        EmployeeContext empContext = new EmployeeContext();
        Employee emp = empContext.Employees.Single(emps => emps.EmployeeId == id);
        return View(emp);
    }

我得到的错误如下:

System.Data.Entity.Core.EntityException was unhandled by user code
Message=The underlying provider failed on Open.
Source=EntityFramework
StackTrace:
   at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
   at System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection(Boolean shouldMonitorTransactions)
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass3.<GetResults>b__1()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
   at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
   at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__3[TResult](IEnumerable`1 sequence)
   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 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.Single[TSource](IQueryable`1 source, Expression`1 predicate)
   at MVC_Trials.Controllers.EmployeeController.Details(Int32 id) in C:\Users\administrator.CRC\Documents\Visual Studio 2010\Projects\MVC Trials\MVC Trials\Controllers\EmployeeController.cs:line 19
   at lambda_method(Closure , ControllerBase , Object[] )
   at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
   at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
   at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
InnerException: System.Data.SqlClient.SqlException
   Message=Cannot open database "MVC_Trials.Models.EmployeeContext" requested by the login. The login failed.
Login failed for user 'Test\Administrator'.
   Source=.Net SqlClient Data Provider
   ErrorCode=-2146232060
   Class=11
   LineNumber=65536
   Number=4060
   Procedure=""
   Server=.\SQLEXPRESS
   State=1
   StackTrace:
        at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
        at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
        at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
        at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
        at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject)
        at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout)
        at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
        at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
        at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
        at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
        at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
        at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
        at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
        at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
        at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
        at System.Data.SqlClient.SqlConnection.Open()
        at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<Open>b__36(DbConnection t, DbConnectionInterceptionContext c)
        at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
        at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)
        at System.Data.Entity.Core.EntityClient.EntityConnection.<Open>b__2()
        at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
        at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
        at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
        at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
   InnerException: 

我不明白为什么给用户'测试\管理员'登录登录失败。错误。


EmployeeContext.cs代码

public class EmployeeContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
}

请帮帮我。提前谢谢。

2 个答案:

答案 0 :(得分:0)

您没有指定要用于上下文的连接字符串,因此它使用默认值。将它添加到您的上下文中,它是一个默认构造函数,它将连接字符串的名称传递给基本上下文类。

public EmployeeContext() : base("EmployeeContext")
{
}

答案 1 :(得分:-1)

你有堆栈跟踪,但你需要看到的是内部异常消息,它将告诉你什么是真正的错误以及导致异常被抛出的原因。