Search code examples
c#.netsql-serverentity-frameworkvisual-studio-2019

Class library project Configuration with DbContext in Visual Studio 2019


I defined a class library project in for Data Access layer and it tries to create DbContext but I face an error like this:

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception.

Which has inner execption:

Could not load file or assembly 'System.Configuration.ConfigurationManager, Version=0.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.

I face this error while App.config and Connection String exist. In fact the App.config would be created when I add ADO.NET Entity Data Model.

I work with visual studio 2019 and SQL Server 2022 and .NET Framework v 4.8.

I redefined connection string.

and also follow this: Similar problem

But

builder.Services.AddEntityFramework()
        .AddSqlServer()
        .AddDbContext<AppContext>(options =>
            options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

doesn't exist for me!


Solution

  • I solved my problem by recreating the project as empty class library and then installed packages Microsoft.EntityFrameworkCore and Microsoft.EntityFrameworkCore.SqlServer and run the below command in PMC:

    Scaffold-DbContext "Data Source=.;Initial Catalog=MyDatabase;Trusted_Connection=true;TrustServerCertificate=True; User Id=myuser; Password=mypassword;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models