6

An error occurred accessing the database. This usually means that the connection to the database failed. Check that the connection string is correct and that the appropriate DbContext constructor is being used to specify it or find it in the application's config file.

I swear I tried everything! Going through this tutorial and struggling to get connection to the database.

My table in SQL Server 2012 is called, "tblEmployee" and the database is called "Sample"

This is the Employee.cs class

[Table("tblEmployee")]
public class Employee
{
    public int EmployeeID { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
    public string Gender { get; set; }
}

This is the employee context model class

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

This is the EmployeeControler

public class EmployeeController : Controller
{
    public ActionResult Details()
    {
        EmployeeContext employeeContext = new EmployeeContext();
        Employee employee = employeeContext.Employees.Single(emp => emp.EmployeeID == 2);
        return View(employee);
    }
}

This is the web.config file

<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
    <parameters>
        <parameter value="v11.0" />
    </parameters>
   </defaultConnectionFactory>
    <providers>
    <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
</entityFramework>

And this is the connection string

<connectionStrings>
    <add name="EmployeeContext" connectionString="Data Source=ADMIN-PC;Initial Catalog=Sample;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False" providerName="System.Data.SqlClient" />
</connectionStrings>

Nothing special on the actual View

@{
ViewBag.Title = "Employee Details";
}

<h2>Employee Details</h2>

<table style="font-family:Arial">
    <tr>
        <td>EmployeeID:</td>
        <td>@Model.EmployeeID</td>
    </tr>
    <tr>
        <td>Name:</td>
        <td>@Model.Name</td>
    </tr>
    <tr>
        <td>Gender:</td>
        <td>@Model.Gender</td>
    </tr>
    <tr>
        <td>City:</td>
        <td>@Model.City</td>
    </tr>
</table>

This is the stack trace

at System.Data.Entity.ModelConfiguration.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.Single[TSource](IQueryable`1 source, Expression`1 predicate)
at MVCDemo.Controllers.EmployeeController.Details() in c:\Users\Admin\Documents\Visual Studio 2013\Projects\MVCDemo\MVCDemo\Controllers\EmployeeController.cs:line 19
at lambda_method(Closure , ControllerBase , Object[] )
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__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f<InvokeActionMethodFilterAsynchronously>b__49()
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Spets
  • 2,391
  • 4
  • 24
  • 26
  • So your SQL Server is called ADMIN-PC, and the window user (application pool) has access? Use SQL Sever Management Studio to verify that you can connect to the database. – Nick.Mc Mar 26 '14 at 03:45
  • Looking at the InnerException, "The provider did not return a ProviderManifestToken string." ugh! – Spets Mar 26 '14 at 03:51
  • Yes @ElectricLlama, I opened up Management Studio and I can connect to the database. That's what I used to make the database in the first place. I even tested the connection by making a Test.udl file on my desktop and testing the connection and it works fine! The server name on the .udl file is listed as "ADMIN-PC". I'm thinking it has something to do with EF code I have – Spets Mar 26 '14 at 03:54
  • Next thing is, you are using `Integrated Security=True` which means use the windows account to connect. Through SSMS and UDL, this is you. Through your app this is probably the application pool identity. You could try using SQL Profiler to compare successful and failed login attempts and it will tell you which windows user is trying to login (if any). You could also temporarily try using a SQL user to verify if this is the issue. – Nick.Mc Mar 26 '14 at 03:56
  • and here's what I found when I checked that Manifest error: http://stackoverflow.com/questions/4741499/how-to-configure-providermanifesttoken-for-ef-code-first – Nick.Mc Mar 26 '14 at 03:59
  • @ElectricLlama I tried both but no luck, I'm going to try and reinstall SQL server in hopes that it might do something. The WEIRD part is that I can pull up the server no problem with the SQL Server Explorer and I can pull up and open up the table. It's got to be something in the syntax cause I can see the server and table. I can even open it in Visual Studio. Is there a way to automatically drag/drop it into the solution and have VisualStudio automatically create the EF code and connection string? Maybe I'm coding the Db part wrong hmm – Spets Mar 26 '14 at 05:49
  • So you tried a SQL User and tried monitoring with Profiler? post back if you want more info. I can help you with the SQL Server side but not much with the VS stuff – Nick.Mc Mar 26 '14 at 08:27
  • @ElectricLlama , yep tried to look at the profiler but it never records when a failed login attempt was made or when VisualStudio makes a login attempt. The only time it seems to pick up login traces is when I relog into MS SQL Server Management Studio – Spets Mar 26 '14 at 18:29

7 Answers7

8

Cause: when you were using IIS, your App Pool user was probably 'ApplicationPoolIdentity'. When connecting to network resources, that will connect as local system (so if in a domain, that would be the domain\computer$ account). Presumably that account does not have access to the SQL DB.

Sort of fix: Your change to IIS Express 'fixed' this, connection was made as current user. Not good if you're planning to ever deploy to IIS though.

Better fix: Change your IIS App Pool user to a true Windows user account, which has access to the SQL DB.

I have just gone through exactly same issue, and can confirm above fixes worked for me.

Chalky
  • 1,624
  • 18
  • 20
  • 1
    I can confirm this did the trick. Way better than my solution so I made this the answer :) cheers! – Spets Jul 05 '14 at 05:27
8

my main project which contains web.config file (contains connection string) was not set as default project. setting it to default project solved the problem.

Reza Abolfathi
  • 3,061
  • 2
  • 18
  • 14
2

I had similar error and fixed. I had more than two modules, when I Set the "start-up project" which module containing my ApplicationDbContext class in the solution. Right-click module >> click "Set as StartUp Project"

1

Soooo after quite a bit of struggle with this whole thing, this is what worked for me:

-1) Uninstalled SQL Server

-2) Reinstalled SQL Server and set a new Instance(INST01)

^^I don't think any of the above actually did anything.

-3) Reconnected to the new server with Visual Studio by going to the SQL Server Object Explorer and locating the new instance.

-4) Went back to SQL Server Management Studio and recreated my simple database.

-5) Under SQL Server Object Explorer I copied the connection string from the database properties.

-6) I changed the Web properties for the Project from Local IIS to IIS Express.

-7) Uninstalled EntityFramework 6

-8) Deleted any reference to Entity Framework in web.config file(this way the code for EF 5 would be inserted upon installation)

-9) Installed EntityFramework 5.0.0 from the Package Manager Console.

-10) Ran the application and it worked.

I'm not 100% sure what the issue was but I think it has something to do with Local IIS and IIS Express. I think changing the EF framework version was necessary to make sure the syntax for calling the table was consistent.

Keep in mind that before all of this, I could establish a connection to the database by simply going into the SQL Server Object Explorer. I could even pull up the table in Visual Studio and see the Data.

Hope this helps someone :)

Spets
  • 2,391
  • 4
  • 24
  • 26
  • Glad you sorted it. You should accept your answer if you can. – Nick.Mc Mar 26 '14 at 23:05
  • May be you can try to uninstall EF5 and reinstall EF6 to check if you can reproduce the problem?if yes,then you very close to the cause,anyway,congrat to solve your problem:-) – V-SHY Mar 27 '14 at 00:33
  • Yes, I have same error message, showed when I initially changed from IIS Express to IIS. Must be identity/permissions not configured issue. Will post answer if I find it. – Chalky Jun 03 '14 at 21:26
  • I ended up just removing entityframework 6 and reinstalling it again to latest version instead of version 5, due to compatibility issue and worked just fine, didn't change anything else. – Alejandro H Jul 26 '19 at 14:46
0

if you're server is 2012 sql express the free edition then your connection string should be like this.

<connectionStrings>
<add name="EmployeeContext" connectionString="Data Source=ADMIN-PC\SQLEXPRESS;Initial       Catalog=Sample;Integrated Security=True;Connect  timeout=15;Encrypt=False;TrustServerCertificate=False"
providerName="System.Data.SqlClient" />

Data Source Should Be=Admin-PC\SQLEXPRESS...

Also take a look at this SQL 2012 Connection Strings

REZR.AMX
  • 59
  • 5
  • 20
0

Update

Refer to DbConfiguration Class,

A class derived from this class can be placed in the same assembly as a class derived from DbContext to define Entity Framework configuration for an application. Configuration is set by calling protected methods and setting protected properties of this class in the constructor of your derived type. The type to use can also be registered in the config file of the application.

DbConfiguration derived class should be in the same assembly as DbContext.

In my case of ADO.NET Entity Data Model, I find my class derived from DbContext at Model1.edmx -> Model1.Context.cs -> Model1.Context.cs.

The codes suppose to configure your manifest token and hope it solves your problem.


Old

I found similar problem discussion here, hope can help you solve your problem.

Refer to moozzyk,

Good news is that to workaround the problem you don't actually have to change the EF code.

EF6 allows configuring services and one of the services allows overriding the default behavior of getting the provider manifest token.

You can register your custom manifest token resolver using code based configuration and either return a hardcoded value (e.g. if you are running always against SqlServer 2012 you would just return "2012") or come up with the version on your own.

This should prevent EF from checking what database version your app is running against.

If you run against different versions of Sql Server you can use DbConnection.ServerVersion property to create a provider manifest token for your database.

Here is an example - you can just copy/paste and it should work because EF should detect the configuration *automatically* (as long as the DbConfiguration derived class is in the same assembly as your context)

public class Configuration : DbConfiguration
{
    public Configuration()
    {
        SetManifestTokenResolver(new ManifestTokenResolver());
    }
}

public class ManifestTokenResolver : IManifestTokenResolver
{
    public string ResolveManifestToken(DbConnection connection)
    {
        // The simplest thing is just to return hardcoded value
        // return "2012";

        try
        {
            connection.Open();

            var majorVersion =
                Int32.Parse(connection.ServerVersion.Substring(0, 2), CultureInfo.InvariantCulture);

            if (majorVersion == 9)
            {
                return "2005";
            }

            if (majorVersion == 10)
            {
               return "2008";
            }

            return "2012";

        }
        finally 
        {
            if (connection.State == ConnectionState.Open)
            {
                connection.Close();
            }
        }
    }
}
V-SHY
  • 3,925
  • 4
  • 31
  • 47
  • 1
    I'm not sure where I put this code. In the EmployeeContext.cs ? Seems like it needs its own class. I'm lost >_> – Spets Mar 26 '14 at 03:43
  • 1
    In my case of ADO.NET Entity Data Model, I find my class derived from DbContext at **Model1.edmx -> Model1.Context.cs -> Model1.Context.cs**. May be you can try to search the keyword *DbContext* – V-SHY Mar 26 '14 at 04:42
  • 1
    I will give that a shot tomorrow morning. I'm also going to try and reinstall SQL Server – Spets Mar 26 '14 at 05:47
  • 1
    I tried this and wasn't successful :(, at least I learned something! – Spets Mar 26 '14 at 18:29
  • 2
    I one-upd your comment cause you tried to help, not sure who downvoted it. – Spets Mar 26 '14 at 18:36
  • You tried to put my DbConfiguration to your DbContext, has same error but no new errors right? Or has new errors?thanks – V-SHY Mar 27 '14 at 00:14
  • then means it really not a solution for your problem,haha – V-SHY Mar 28 '14 at 02:13
0

I am also facing the same problem while hosting my MVC application over the IIS. Error: Cannot open database "MVCDemo" requested by the login. The login failed. Login failed for user 'IIS APPPOOL\ASP.NET v4.0'.

Temporary Fix for local user not for deployment :Instead of deploying on IIS , we can use over IISExpress, Go to Project-->Properties-->Web-->Enable radio button for ,Use Local IIS server and checkmark the setting Use IIS Express.

System Speci: VS 2012,