简体   繁体   中英

Integrating Entity Framework Core into Class Library (.NET Standard)

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.

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:

在此处输入图像描述

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM