簡體   English   中英

.NET Core 2.x從dbcontext類中的appsettings.json獲取連接字符串

[英].NET Core 2.x get connection string from appsettings.json in dbcontext class

我在DBContext類中設置連接字符串時遇到問題。 我知道我可以在SqlLiteDbcontext構造函數中注入IConfiguration或使用IOption模式,但是在CRUD.cs中,我已經使用了無參數構造函數。 我正在尋找不需要修改CRUD.cs的解決方案。

    public class SqliteDbContext : DbContext
    {
        public SqliteDbContext() : base()
        {
        }

        public SqliteDbContext(DbContextOptions<SqliteDbContext> options) : base(options)
        {
        }
 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlite("Data Source=App_Data/sqlite.db");

            optionsBuilder.EnableSensitiveDataLogging(true);
        }

Startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(IISDefaults.AuthenticationScheme);
            services.AddMemoryCache();
            services.AddMvc();
            // Adds services required for using options.
            //services.AddOptions();

            services.Configure<MvcOptions>(options =>
            {
            });

            services.AddDbContext<SqliteDbContext>(options =>
                options.UseSqlite(Configuration.GetConnectionString("Sqlite")));

CRUD.cs

 public partial class CRUD<T> where T : class, ICreatedDate, IId
    {
        private SqliteDbContext db;
        private DbSet<T> DbSet => db.Set<T>();

        public List<T> Read()
        {
            using (db = new SqliteDbContext())
            {
                return DbSet.ToList();
            }
        }
//...

您不應該在ASP.NET Core中使用實體框架。 您具有依賴項注入和正確配置的EF上下文,因此您應該利用它。 這實質上意味着:

  1. 切勿使用new手動創建數據庫上下文。 始終將上下文注入為依賴項。
  2. 不要覆蓋數據庫中的OnConfiguring方法來配置上下文。 預期配置將作為DbContextOptions傳遞,以便上下文本身不負責設置配置。
  3. 避免為數據庫上下文使用空的構造函數,以避免在上下文未配置的地方濫用。

因此,您的代碼應如下所示:

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

    // define your database sets
    public DbSet<Entity> Entities { get; set; }
}

public class CRUDService<T>
{
    private readonly SqliteDbContext db;
    CRUDService(SqliteDbContext database)
    {
        db = database;
    }

    public List<T> Read()
    {
        return db.Set<T>().ToList();
    }
}

SqliteDbContext將由依賴項注入容器自動提供。 您只需要注入依賴關系就可以正確解決它。

順便說一句。 我通常建議您避免使用(通用)存儲庫模式。 Entity Framework中的數據庫上下文已經是工作單元,每個數據庫集已經是一個存儲庫。 因此,您可以直接使用它。 在其之上添加另一個抽象(尤其是通用的抽象)並沒有什么好處,因為這總是會限制您。

另外,您應該將SqliteDbContext重命名為實際上描述了上下文管理的數據的名稱。 上下文不應該關心正在使用什么基礎數據庫提供程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM