简体   繁体   中英

MVC Connection Error : The underlying provider failed on Open

I am new to ASP.NET MVC4. I'm trying to connect database using entity framework but didn't succeeded.
connection string is as follows

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

I am fetching data using following code:

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

I am Getting error as follows:

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: 

I didn't understand why its giving Login failed for user 'Test\\Administrator'. error.


EmployeeContext.cs code

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

Please help me out. Thanks in advance.

You are not specifying the connection string to use for your context so it's using the default one. Add this to your context, it is a default constructor which will pass the name of the connection string to the base context class.

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

您拥有堆栈跟踪,但是您需要查看的是内部异常消息,该消息将告诉您真正错误的原因以及导致引发异常的原因。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM