从类库中读取放置在 ASP.NET Core 中的连接字符串.数据库优先 [英] Reading connection string placed in ASP.NET Core from class library. Database First

查看:13
本文介绍了从类库中读取放置在 ASP.NET Core 中的连接字符串.数据库优先的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

项目结构如下:

  • 汽车(ASP.NET Core MVC.这里有一个连接字符串)

Cars.Persistence(ASP.NET Core 类库.这里我们有存储库,数据库优先)

Cars.Persistence (ASP.NET Core Class library. Here we have Repository, Database First)

我通过以下来自 此 msdn 文档:

Scaffold-DbContext "Server=PCSQL2014XP;Database=Cars;Trusted_Connection=True;" 
    Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

到目前为止一切顺利.但是,现在 carsContextCars.Persistence - ASP.NET Core 类库中具有硬编码的连接字符串:

So far so good. However, now carsContext has hard coded connection string in Cars.Persistence - ASP.NET Core Class library:

public partial class carsContext: DbContext
{
    public carsContext()
    {
    }

    public carsContext(DbContextOptions<carsContext> options)
        : base(options)
    {
    }

    public virtual DbSet<Cars> Cars { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer("Server=PCSQL2014XP...");// hard coded 
                                                                  // connection string
        }
    }
}

起初,我想在我的类库Cars.Persistence中创建自己的appsettings.json.但是,根据这篇文章,不建议使用 appsettings.json 类库中的文件..

At first, I thought to create own appsettings.json in my class library Cars.Persistence. However, according to this post it is not advisable to have appsettings.json file in Class Library..

我已经阅读此方法,但是,如果我再次运行此命令,则硬编码字符串将再次出现:

I've read this approach, however, the hard coded string will appear again, if I will run this command again:

Scaffold-DbContext "Server=PCSQL2014XP;Database=Cars;Trusted_Connection=True;" 
        Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

所以我的问题是如何在我的类库 Cars.Persistence 中使用连接字符串(位于 Cars 项目中)?

So my question is how can I use connection string(located in Cars project) in my class library Cars.Persistence?

更新:

我已注释掉以下代码:

public partial class eshopContext : DbContext
{

     public eshopContext(DbContextOptions<eshopContext> options): base(options)
     {} 

     // public eshopContext(){}        

      /*protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
     {
         if (!optionsBuilder.IsConfigured)
         {
             #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
             optionsBuilder.UseSqlServer("Server=...");
         }

      }*/

 }

推荐答案

您可以利用 .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;
    }

这篇关于从类库中读取放置在 ASP.NET Core 中的连接字符串.数据库优先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆