【问题标题】:How to add db context not in ConfigureServices method ASP.NET Core如何在 ConfigureServices 方法 ASP.NET Core 中添加数据库上下文
【发布时间】:2019-05-14 19:51:53
【问题描述】:

是否可以在外部类/方法中“即时”添加数据库上下文?当我运行应用程序时,没有任何连接字符串,所以我需要在输入一些信息(服务器、数据库名称、等)后生成一个数据库

【问题讨论】:

标签: asp.net-core entity-framework-core


【解决方案1】:

一种方法是使用工厂模式,即创建一个服务,用于创建上下文的新实例。

这是一个示例,它不是最终解决方案,您需要根据自己的需要对其进行调整,但它应该让您了解该技术:

public interface IDbContextFactory
{
    DbContext CreateDbContext(string connectionString);
}

public class DbContextFactory : IDbContextFactory
{
    public DbContext CreateDbContext(string connectionString)
    {
        return new DbContext(connectionString);
    }
}

然后在asp.net core中,你可以注册上下文工厂并注入到你的控制器中:

 services.AddSingleton<IDbContextFactory, DbContextFactory>();

 public class SomeController
 {
      private IDbContextFactory contextFactory;

      public SomeController(IDbContextFactory contextFactory)
      {
          this.contextFactory = contextFactory;
      }

      public IActionResult Index()
      {     
         using(var db = contextFactory.CreateDbContext("Your connection string"))    {
              //Get some data
         }
         return View();
     }
 }

您可以将工厂模式与工作单元和/或存储库模式结合起来,而不是创建 DbContext,以更好地分离关注点并确保您始终处置上下文等...

【讨论】:

  • 这个答案让我解决了我自己使用 .net core 2.1 / signalr core 的解决方案,并且需要设置一个 dbContextFactory,因为普通的 dbContext 被放置在集线器内。这里唯一需要的小更新(对于更高版本)现在我们调用IDesignTimeDbContextFactory,而不是IDbContextFactory。更多信息可以在这里找到:https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dbcontext-creation
【解决方案2】:

使用new YourContext(new DbContextOptionsBuilder&lt;YourContext&gt;().Use...().Options)

【讨论】:

    猜你喜欢
    • 2023-01-19
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 2021-05-11
    相关资源
    最近更新 更多