且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从类库中读取放置在 ASP.NET Core 中的连接字符串.数据库优先

更新时间:2023-02-17 08:37:32

您可以利用 .Net Core Dependency Injection 和开箱即用的功能.您的连接字符串将保留在 Web 项目中,但您可以使用 DB 上下文而无需在类库项目中声明任何连接字符串.我正在分享我现有项目中的代码示例.

You can take the advantage of .Net Core Dependency Injection and out of box features. Your connection string will remain in web project but you can use DB context without declaring any connection string in Class Library Project. I am sharing code sample from my existing project.

设置连接字符串

您在启动时引用了连接字符串并添加到服务中.您不需要再次定义连接字符串并使用内置 DI 使用 db 上下文.代码看起来像这样!

You have referenced connection string in your start up and added to services. You don't need to define the connection string again and use the db context using Built in DI. The code could look like this !

启动班

设置您的 SQL 配置.仔细查看 MigrationsAssembly,您可以在此处引用您的类库项目.

Set up your SQL config. Look closely at MigrationsAssembly this is where you would reference your class library project.

public static IServiceCollection AddCustomDbContext(this IServiceCollection services, IConfiguration configuration)
{

    // Add DbContext using SQL Server Provider
    services.AddDbContext<PaymentDbContext>(options =>
        options.UseSqlServer(configuration.GetConnectionString("myconnectionstring"), x => x.MigrationsAssembly("Payment.Persistence")));

    return services;
}

上下文类

这个类在你的类库项目中.

This class is in your class library project.

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

        }

        public DbSet<Payments> Payments { get; set; }    


    }    

使用 DI 访问上下文

    private readonly PaymentDbContext _context;


     public PaymentsRepository(PaymentDbContext dbContext)
     {
     _context = dbContext;
    }