从dbContext获取连接字符串,用于db迁移net5.0中的db迁移

发布于 2025-02-08 09:56:08 字数 2172 浏览 2 评论 0原文

我有一个使用EF的Azure函数解决方案。我正在将dbContext注入startup.cs类中。

我的项目布局

  • project>。函数(startup.cs,function class) - 设置为启动项目
  • 项目>。基础架构(拥有DBContextClass类,生成的db表模型)

appsettings.json

  "ConnectionStrings": {
    "MyDbCon": "Server=xxxx..............."
  },

startup.cs

public override void Configure(IFunctionsHostBuilder builder)
{
.....
    serviceCollection.AddDbContext<MySampleContext>(options =>
    {
        options.UseSqlServer(configuration.GetConnectionString("MyDbCon"));
    });
...
}

dbContext类(mySampleContext.cs)

public partial class MySampleContext : DbContext
{
   private string connectionString;

   public MySampleContext()
   {

   }

   public MySampleContext(DbContextOptions<MySampleContext> options, IConfiguration   configuration) : base(options)
   {
        var sqlServerOptionsExtension = options.FindExtension<SqlServerOptionsExtension>();
        if (sqlServerOptionsExtension != null)
        {
            this.connectionString = sqlServerOptionsExtension.ConnectionString;
        }
   }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(this.connectionString);
        }
    }
 ...
}

当我本地运行函数时,dbContext是注入预期。调用了参数化的结构,我能够获得连接字符串。所有好

但是当我尝试运行以下命令

dotnet ef migrations script --output .\Infrastructure\Migrations\migration_script.sql --startup-project .\Functions --project .\Infrastructure

 Add-Migration InitialCreate

从packageManager控制台im im fer Orror时:值不能为null。 (参数为“连接”)。我知道这是因为正在使用默认结构,而连接字符串正式字符串

   public MySampleContext()
   {

   }

全部还可以,但是连接字符串是null,但是如何获得连接字符串(使用默认结构),以便我能够运行EF命令上面没有硬编码连接字符串?

public MySampleContext()
{
    this.connectionString = "Server=........";
}

I have a Azure function solution which is using EF. I'm injecting the DBContext in the startup.cs class.

My project layout

  • Project>.Function (Startup.cs, Function classes ) - Set as startup project
  • Project>.Infrastructure (Has the DBContext class, Generated DB table Models)

appsettings.json

  "ConnectionStrings": {
    "MyDbCon": "Server=xxxx..............."
  },

Startup.cs

public override void Configure(IFunctionsHostBuilder builder)
{
.....
    serviceCollection.AddDbContext<MySampleContext>(options =>
    {
        options.UseSqlServer(configuration.GetConnectionString("MyDbCon"));
    });
...
}

DBContext class (MySampleContext.cs)

public partial class MySampleContext : DbContext
{
   private string connectionString;

   public MySampleContext()
   {

   }

   public MySampleContext(DbContextOptions<MySampleContext> options, IConfiguration   configuration) : base(options)
   {
        var sqlServerOptionsExtension = options.FindExtension<SqlServerOptionsExtension>();
        if (sqlServerOptionsExtension != null)
        {
            this.connectionString = sqlServerOptionsExtension.ConnectionString;
        }
   }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(this.connectionString);
        }
    }
 ...
}

When i run the function locally, the DBContext is injected as expected. The parameterised constructure is called and im able to get the connection string. All good

BUT when i try to run the following commands

dotnet ef migrations script --output .\Infrastructure\Migrations\migration_script.sql --startup-project .\Functions --project .\Infrastructure

or

 Add-Migration InitialCreate

from the PackageManager Console im getting error: Value cannot be null. (Parameter 'connectionString'). This I know is because the default constructure is being used and the connecting string is null

   public MySampleContext()
   {

   }

When I hardcode the connection string all is Ok, but How do I get the connection string (using the default constructure) so I'm able to run EF commands above without hardcoding the connection string?

public MySampleContext()
{
    this.connectionString = "Server=........";
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

许一世地老天荒 2025-02-15 09:56:08

这里有3个部分 -

  1. 从设置(Local.settings.json)获取连接字符串。
  2. Azure函数的EF(Code -First),
  3. 设置具有Azure函数生成迁移的
  4. 从而使其在Azure 第1部分上都起作用

:连接字符串 -

在您的 local.settings.json.json 中添加以下内容-

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "AzureWebJobsSecretStorageType": "files",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "MyDbCon": "your-connection-string-here",
}

然后在您的启动代码中,使用它 -

builder.Services.AddDbContext<MySampleContext>(options =>
{
    options.UseSqlServer(Environment.GetEnvironmentVariable("MyDbCon"));
});

第2部分:使用Azure函数设置EF -

如果您先执行代码,则需要一些设置。为EF核心定义了以下步骤,EF应该相同。

添加以下nugets

  1. -microsoft.entityframeworkcore.design
  2. microsoft.entityframeworkcore.tools

如果您的data -access project与主项目分开,则 gratsityframeworkworkeworkworkwork.design.design.design nuget to Maint项目

现在,创建一个称其为“ mySampleContext”旁边的文件 - mySamplecontextFactory 并添加以下内容 -

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;

namespace MySampleProject.DataAccess
{
    public class MySampleContextFactory: IDesignTimeDbContextFactory<MySampleContext>
    {
        public MySampleContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<MySampleContext>()
                .UseSqlServer(Environment.GetEnvironmentVariable("MyDbCon"));

            return new MySampleContext(optionsBuilder.Options);
        }
    }
}

因此,您的mySamplecontext现在将拥有一个构造函数,例如 -

public MySampleContext(DbContextOptions<MySampleContext> options) : base(options)
{
    // add other required code here
}

part 3 :生成迁移,

为此 生成迁移打开您的软件包管理器控制台,将连接字符串添加到环境中作为变量,以便可以将其拾取。

确保选择数据访问项目(如果不是您的主要项目)

,请输入以下内容 -

$env:MyDbCon="your-connection-string-here"

”

  • 注意:如果您仍然找到连接字符串未找到错误,您,您'二
    需要重新启动Visual Studio并再次输入上述。

现在,您可以继续使用“软件包管理器”控制台中的普通EF迁移命令(请选择数据访问库/项目) -

add-migration InitialCreate
update-database

这足以让所有这些都可以在本地工作。但是,一旦出版,就涉及更多步骤可以使其起作用。

第4部分:使其在云中都起作用,

以将迁移应用于您的云SQL(例如Azure上的SQL数据库),您需要将“ Update-Database”应用于Cloud-SQL Connection字符串。因此,您需要重新启动Visual Studio并输入新的Connection String,

$env:MyDbCon="sql-db-cloud-conn-string"
update-database

最后,才能在发布一旦发布Azure功能,您需要将MyDBCON添加到门户网站的应用程序设置中。

转到门户中的功能应用程序,然后添加以下&amp;然后单击保存 -

”在此处输入图像描述“

”在此处输入图像描述”

There are 3 parts here -

  1. Getting connection string from settings (local.settings.json).
  2. Setting up EF (code-first) with Azure Functions
  3. Generating Migrations
  4. Making it all work on Azure

Part 1: For connection string -

In your local.settings.json add the following -

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "AzureWebJobsSecretStorageType": "files",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "MyDbCon": "your-connection-string-here",
}

Then in your startup code, use it like this -

builder.Services.AddDbContext<MySampleContext>(options =>
{
    options.UseSqlServer(Environment.GetEnvironmentVariable("MyDbCon"));
});

Part 2: Setting up EF with Azure Function -

This one requires a bit of setup if you're doing code first. The following steps are defined for EF Core, it should be the same for EF.

Add the following nugets -

  1. Microsoft.EntityFrameworkCore.Design
  2. Microsoft.EntityFrameworkCore.Tools

If your data-access project is separate from the main project, then add the Micrsoft.EntityFrameworkCore.Design nuget to the main project as well.

Now create a file next to your "MySampleContext" calling it - MySampleContextFactory and add the following -

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;

namespace MySampleProject.DataAccess
{
    public class MySampleContextFactory: IDesignTimeDbContextFactory<MySampleContext>
    {
        public MySampleContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<MySampleContext>()
                .UseSqlServer(Environment.GetEnvironmentVariable("MyDbCon"));

            return new MySampleContext(optionsBuilder.Options);
        }
    }
}

So your MySampleContext will now have a constructor like -

public MySampleContext(DbContextOptions<MySampleContext> options) : base(options)
{
    // add other required code here
}

Part 3: Generating Migrations

For this open your package manager console, add the connection string to the environment as a variable so the MySampleContextFactory can pick it up.

Ensure the data-access project is selected (if it isn't your main project)

In the package manager console, enter the following -

$env:MyDbCon="your-connection-string-here"

enter image description here

  • Note: If you still get the connection string not found error, you'll
    need to restart visual studio and enter the above again.

Now you can continue with the normal EF migration commands in the package manager console (do select the data-access library/project) -

add-migration InitialCreate
update-database

This is enough for it all to work locally. But few more steps are involved to make it work once its published.

Part 4: Making it all work in the cloud

To apply the migration to your Cloud SQL (e.g. SQL Database on Azure), you need to apply the "update-database" with your cloud-sql connection string. So you need to restart Visual Studio and enter the new connection string,

$env:MyDbCon="sql-db-cloud-conn-string"
update-database

Finally, for it to work on Azure Function once published, you need to add the MyDbCon to the application settings in the portal.

Go to your Function App in the portal and add the following & then click SAVE -

enter image description here

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文