4

I have an ASP.NET Core web app and a class library project in a single solution. My intention is to use the .NET Core web app just to serve as a web application and not use as a data layer. I have created the separate class library project for the sole purpose of creating the entity classes interact with the database. And I have included the entity framework core libraries into the class library project.

  1. How can I include multiple configuration files (based on the environment, like appsettings.development.json, appsettings.production.json etc.) and read those values based on the environment I set?

  2. How can I register the DbContext class in the class library, like in a ASP.NET Core web app below ?

This is a snippet of my ASP.NET Core web app Startup class

public void ConfigureServices(IServiceCollection services)
{
    var connString = Configuration.GetConntectionString("ConnectionStringKey");

    services.AddDbContext<MyDbContext>(options => options.UseSqlServer(connString));

    // other service configuration
}

Your input is much appreciated.

1 Answer 1

5

Add these packages in your Class Library.

 <PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.1" />
 <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
 <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0" />

Create a static class to register DbContext

public static  class ISserviceCollectionExtension
    {
        public static IServiceCollection configureservice(this IServiceCollection service, IConfiguration Configuration)
        {
            //access the appsetting json file in your WebApplication File

            string filePath = @"C:\your Web App path\appsettings.json";

            Configuration = new ConfigurationBuilder()
               .SetBasePath(Path.GetDirectoryName(filePath))
               .AddJsonFile("appSettings.json")
               .Build();

            service.AddDbContext<AppDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("xxx")));
            return service;
        }
    }

DateContext

 public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {

        }
    
        public DbSet<xx> xx{ get; set; }
        //.......
    }

When you add migration, You may get the error like this:

enter image description here

Now you need create DbContextFactory class

public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
    {
        public AppDbContextFactory()
        {

        }

        private readonly IConfiguration Configuration;
        public AppDbContextFactory(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public AppDbContext CreateDbContext(string[] args)
        {

            string filePath = @"C:\Users\Administrator\source\repos\CheckPoint\NullMVC\appsettings.json";

            IConfiguration Configuration = new ConfigurationBuilder()
               .SetBasePath(Path.GetDirectoryName(filePath))
               .AddJsonFile("appSettings.json")
               .Build();


            var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
            optionsBuilder.UseSqlServer(Configuration.GetConnectionString("xxx"));

            return new AppDbContext(optionsBuilder.Options);
        }
    }

Finally, You can register and Migration DBContext in Class Library successfully.

The first question, You can refer to this issue.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for your answer - I apologize that I am new to EF, but I don't understand where to go with your last statement: "Finally, You can register and Migration DBContext in Class Library successfully." I am struggling with how do I instantiate the Data Access Library from the Web app, and how do I instantiate the DbContext in the DLL. Do I instantiate the DAL in the Web Program.cs, or in each web page? How? I want to take the connection string from web appsettings and pass it to the DLL as an argument...
In fact, it is NOT my intent to perform a migration - I have an existing DB that I want to code around, so I just need to build code that will interact with it.
this seems to be rather complicated, in .Net (core) 8, just create a class library project, in the nugget manager console (vs 2022), run Scaffold-DbContext and everything will be generated (models, dbContext, ...) that can referenced in an api project, ui, .... A big problem is when you Scaffold-DbContext you can't use a connection string in an appSettings.json, if you can tell me !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.