An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code, C#

.net c# database entity-framework

Question

Im trying to work with databases and Entity-framework.

Here Is my Database:

Database

I have the following file that creates an context:

namespace SportsStore.domain.Concrete
{
    //Associate the model with the database
    //This class then automatically defines a property for each table in the database that I want to work with. 
    public class EFDbContext : DbContext { 


        public DbSet<Product> Products { get; set; }

        /*protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }*/
    }
}

Here IS my file that Initialize the context-class:

namespace SportsStore.domain.Concrete
{
    public class EFProductRepository : IProductRepository
    {
        private EFDbContext context = new EFDbContext();

        public IEnumerable<Product> Products
        {
            get { return context.Products.ToList(); } 
        }
    }
}

When I run my application, I get the following error:

An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code

Additional information: Failed to set database initializer of type 'SportsStore.domain.Concrete, EFProductRepository' for DbContext type 'SportsStore.domain.Concrete, EFDbContext' specified in the application configuration. See inner exception for details.

Here Is the details message of the inner exception:

Can not load file or assembly EFDbContext or one of its dependencies. The system can not find the file EFDbContext

Here Is my App.config:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
        <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
      </configSections>
      <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
          <parameters>
            <parameter value="mssqllocaldb" />
          </parameters>
        </defaultConnectionFactory>
        <providers>
          <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
        </providers>
      </entityFramework>
      <connectionStrings>
        <add name="EFDbContext" connectionString="data source=(LocalDb)\MSSQLLocalDB;initial catalog=SportsStore.domain.Concrete;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
      </connectionStrings>
    </configuration>

Here is my Web.Config:

 <?xml version="1.0" encoding="utf-8"?>
    <!--
      For more information on how to configure your ASP.NET application, please visit
      http://go.microsoft.com/fwlink/?LinkId=301880
      -->
    <configuration>
      <configSections>
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
      <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
      <appSettings>
        <add key="webpages:Version" value="3.0.0.0" />
        <add key="webpages:Enabled" value="false" />
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
      </appSettings>
      <system.web>
        <compilation debug="true" targetFramework="4.5.2" />
        <httpRuntime targetFramework="4.5.2" />
      </system.web>
      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
          </dependentAssembly>
        </assemblyBinding>
      </runtime>
      <system.codedom>
        <compilers>
          <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
          <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
        </compilers>
      </system.codedom>
      <entityFramework>

        <contexts>
          <context type="SportsStore.domain.Concrete, EFDbContext">
            <databaseInitializer type="SportsStore.domain.Concrete, EFProductRepository" />
          </context>
        </contexts>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
          <parameters>
            <parameter value="mssqllocaldb" />
          </parameters>
        </defaultConnectionFactory>
        <providers>
          <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
        </providers>
      </entityFramework>
    </configuration>

How does it know which database to use?

I'm new to Entity framework and databases in .NET.

1
0
8/25/2019 12:23:02 PM

Accepted Answer

In your Web.config file you have the following configuration:

<configuration>
  <entityFramework>
    <contexts>
      <context type="SportsStore.domain.Concrete, EFDbContext">
        <databaseInitializer type="SportsStore.domain.Concrete, EFProductRepository" />
      </context>
    </contexts>
  </entityFramework>
</configuration>

Here you specify that the assembly EFDbContext contains a context type SportsStore.domain.Concrete that should be initialized by initializer type SportsStore.domain.Concrete in assembly EFProductRepository.

Some of these names looks rather unorthodox. Combined with the underlying error that The system can not find the file EFDbContext my guess is that you need to go through this configuration and fix it.

  • Do you have one or two assemblies? If only one then specify the correct name in the configuration.
  • Are the context and the initializer specified by the correct type? If not correct the type names.
  • Do you even have an initializer? If not remove the configuration completely from Web.config. EFProductRepository is certainly not an initializer.

You specify a type in a configuration file like this:

[Fully qualified name of type including namespace], [Name of assembly without .DLL]

So to specify you context assuming the assembly name is EFDbContext you write this:

SportsStore.domain.Concrete.EFDbContext, EFDbContext

The assembly name is probably wrong based on the error that you get but only you know the correct name.

1
10/13/2015 7:00:37 AM

Popular Answer

I have always solved this issues in ASP.NET Scaffolding with VS using the following commando on the PM console (Package Manager Console)

PM> Update-Database  -Force

That should be work for you!



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow