System.Data.DataException error occurred in EntityFramework.dll
Asked Answered
C

3

10

I have been following this tutorial Getting Started with Entity Framework 6 Code First using MVC 5.

When I got to the section where I need to run the program and click on Student so that the program would create database I get the following error.

enter image description here

System.Data.DataException was unhandled by user code HResult=-2146233087 Message=An exception occurred while initializing the database. See the InnerException for details. Source=EntityFramework StackTrace: at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() at System.Data.Entity.Internal.LazyInternalContext.b__4(InternalContext c) at System.Data.Entity.Internal.RetryAction1.PerformAction(TInput input) at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1 action) at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase() at System.Data.Entity.Internal.InternalContext.Initialize() at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) at System.Data.Entity.Internal.Linq.InternalSet1.Initialize() at System.Data.Entity.Internal.Linq.InternalSet1.GetEnumerator() at System.Data.Entity.Infrastructure.DbQuery1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() at System.Collections.Generic.List1..ctor(IEnumerable1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source) at ContosoUniversityFollow.Controllers.StudentController.Index() in c:\Users\Office\Documents\Visual Studio 2013\Projects\ContosoUniversityFollow\ContosoUniversityFollow\Controllers\StudentController.cs:line 21 at lambda_method(Closure , ControllerBase , Object[] ) at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) at System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod() at System.Web.Mvc.Async.AsyncControllerActionInvoker.b__36(IAsyncResult asyncResult, ActionInvocation innerInvokeState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.End() at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag) at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3c() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass45.b__3e() InnerException: System.Data.Entity.Core.EntityException HResult=-2146233087 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() at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) at System.Data.Entity.Core.Objects.ObjectQuery1.<>c__DisplayClassb.b__9() at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation) at System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption) at System.Data.Entity.Core.Objects.ObjectQuery1..GetEnumerator>b__0() at System.Lazy1.CreateValue() at System.Lazy1.LazyInitValue() at System.Lazy1.get_Value() at System.Data.Entity.Internal.LazyEnumerator1.MoveNext() at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source) at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__1[TResult](IEnumerable1 sequence) at 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](IQueryable1 source) at 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.DropCreateDatabaseIfModelChanges1.InitializeDatabase(TContext context) at 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, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) at 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, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry) at 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](Func1 operation) at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation) at System.Data.Entity.Core.EntityClient.EntityConnection.Open() InnerException:

I have a hard time trying to fix the problem. I follow everything and even redo it just to make sure I got it right. I don't think I miss any steps. But there is something wrong. If I run the whole sample code, everything works fine.

Any help is appreciated.

Thanks,

Pheap

EDIT:

It was really frustrating for a simple thing that lead to an error like this. @mmeasor, I just saw that error as well. It cannot connect to database. So that lead me to check the connection.

What happen was that at first I used this connection string: enter image description here

So EntityFramework created a database file ContosoUniversity1.mdf in here like C:\Users\Office\ContosoUniversity1.mdf. But then I want it to create another one and use that instead and this time I want it to be in the program App_Data\ folder instead.

So I modified the web.config file to: enter image description here

I thought if I do that, EF will create a new database for me in the \App_Data\ folder and link to that instead of the old on in C:\Users\Office.

I was so wrong! that was when I start getting the error posted above. And I cannot find what causes the problem.

With the second web.config, I tried to copy the database file to the App_Data folder, but that still doesn't work.

Now I use the first connection string and it works fine.

So now the question is: How to make the program links to database file in the \App_Data\ folder instead?

Thanks,

Pheap

Chlamys answered 21/3, 2014 at 20:17 Comment(1)
did you look at the inner exception? it says the login failed for Office-PC\Office. make sure that user has access to the database, and that you have the right passwordAyrshire
A
2

I had the same problem in trying to change location of Conosto University tutorial database from User folder to App_Data folder. John Locke keyed me into the idea that it may have something to do with having to change the name of the database.

Change name slightly of database named in the web.config file (This works inconsistently, but does work consistently inconsistently. If I had to test this again...and I'm sure I will at some point...I would stay away from reusing names - i.e. don't toggle back and forth between two name preferences (e.g. database1 and database2 back to database1 - I would use completely novel names e.g. databse7...database8...database9 - get name away from previously used names)

I also had luck, once a database was created with the name I didn't want, changing the database name to what I wanted it to be and matching that name in web.config (i.e. I was able to create a "database3.mdf" file successfully and then changed it in the OS to what I wanted - "database1.mdf" and matched the web.config file to database1 and it connected up on the first try)

Afroasiatic answered 10/6, 2014 at 14:10 Comment(1)
The "change the database name" worked like a champ. My scenario was I had been working through some o365 labs with had a class creating a datacontext. On my second pass through the labs, it couldn't create the db, even though it was going to local App_Data. Changing the database name to be unique fixed the problem. Lab I was working on was github.com/OfficeDev/TrainingContent/blob/master/O3651/…Pinole
D
0

I had this problem for days ("An exception of type 'System.Data.DataException' occurred in EntityFramework.dll but was not handled in user code") and I tried everything since changing the connection string to many different methods I saw on Internet questions and answers, My solution?... Created a new proyect with another name, and it saved me.

Diannadianne answered 26/7, 2018 at 17:35 Comment(0)
C
-1

Here EmployeeDetail is a table name and Employee is a model name. And ID,Branch, Salary and UID are table fields:

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);
}

view page code

<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>
Clarkclarke answered 11/5, 2016 at 10:59 Comment(1)
Please elaborate on how this code answers the question.Allerie

© 2022 - 2024 — McMap. All rights reserved.