簡體   English   中英

如何配置UseSqlServer?

[英]How to configure UseSqlServer?

我正在嘗試將應用程序配置為使用我的 class(派生自DbContextApplicationDbContext連接到我的數據庫。 我已經制作了配置文件appsetting.json

"Data": {
    "SportStoreProducts": {
        "ConnectionStrings":"Server=(localdb)\\MSSQLLocalDB;Database=SportStore;Trusted_Connection=True;MultipleActiveResultSets=true"
    }
}

我使用依賴注入通過 Startup 構造傳遞 object 實現IConfiguration (即appsetting.json ):

public class Startup
{
    public Startup(IConfiguration configuration) => Configuration = configuration;

    public IConfiguration Configuration { get; }
}

現在我想在StartupConfigureServices方法中使用這個配置文件,並使用擴展方法AddDbContext注冊我的ApplicationDbContext以使用我在配置文件中分配的 SQL 數據庫( SportStore ):

public void ConfigureServices(IServiceCollection services)
{
        services.AddDbContext<ApplicationDbContext>(
            options => options.UseSqlServer(***);
}

我的問題是,我應該將什么作為參數 (***) 傳遞給UseSqlServer方法,以便它可以使用我提供的配置屬性將上下文連接到 SQL 服務器數據庫?

 services.AddDbContext<BloggingContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("ConnectionStrings")));

有關更多詳細信息,請參閱 -> 鏈接

抱歉,可能有些晚了,但是:

  1. 安裝包 Microsoft.EntityFrameworkCore.SqlServer
  2. 添加參考: using Microsoft.EntityFrameworkCore;

對於 .NET 6.0,只需執行以下操作:

builder.Services.AddDbContext<cursosContext>(options => options.UseSqlServer("name=ConnectionStrings:NombreCadena"));

optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=your_database_name_here;Trusted_Connection=True;");

暫無
暫無

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

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