【问题标题】:How do you construct Entity Framework Core IdentityDbContext<> outside of a service?如何在服务之外构建 Entity Framework Core IdentityDbContext<>?
【发布时间】:2018-02-28 22:53:35
【问题描述】:

我很好奇,因为通常你可以在没有 IdentityDbContext 的情况下做到这一点:

public class SomeContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
             //I am using Postgres but will also accept answers to SQL Server as I want both ultimately
              optionsBuilder.UseNpgsql(@"Host=localhost;Database=someDb;Username=user;Password=yeah");
        }
    }
}

但是当我转到“IdentityDbContext”时,我的 OnConfiguring 方法消失了。看来这真的不再连线了,除非我正在启动一项服务并执行类似于以下启动的操作:

services.AddDbContext<SomeContext>(cfg =>
{
    cfg.UseSqlServer(_config.GetConnectionString("MyConnectionString"));
});

如果我正在执行一项服务并且 EF Core 位于同一个包含的项目中,那就太好了。但如果我不是呢?您不能在构造函数或其他实例化方法中动态指定连接字符串吗?

【问题讨论】:

    标签: entity-framework connection-string entity-framework-core


    【解决方案1】:
    • appsettings.json - 添加连接字符串:

    {
      "Logging": {
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "AllowedHosts": "*",
      "ConnectionStrings": {
        "SomeDatabase": "Host=localhost;Database=...;Username=...;Password=..."
      }
     }
    
    • 更新 Startup.cs

      public void ConfigureServices(IServiceCollection services)
      {
          services
              .AddMvc()
              .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
              .AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);
      
          services
              .AddEntityFrameworkNpgsql()
              .AddDbContext<SomeContext>(options => options.UseNpgsql(Configuration.GetConnectionString("SomeDatabase")))
              .BuildServiceProvider();
      }
      
    • 注入控制器:

      private SomeContext _db;
      public SomeController(SomeContext someContext)
      {
          _db = someContext;
      }
      

    【讨论】:

      猜你喜欢
      • 2017-11-19
      • 2021-02-04
      • 2017-10-04
      • 2019-02-13
      • 1970-01-01
      • 2022-08-20
      • 2022-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多