【问题标题】:How inject 2 db context to .Net Azure Functions?如何将 2 db 上下文注入 .Net Azure Functions?
【发布时间】:2022-06-10 18:56:50
【问题描述】:

我希望能够在 .Net Azure Functions 解决方案中通过注入查询 2 个数据库,我注入了一个实体 DbContext 并且工作正常,但是如何在 Startup.cs 上注入另一个上下文?这是我的实际代码:

MyDbContext.cs

namespace AzFunc.Library.MyDbContext
{

public partial class MyDbContext: DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options)
        : base(options)
    {
        this.ChangeTracker.LazyLoadingEnabled = false;
    }

    public virtual DbSet<User> Users{ get; set; }
}

CustomContexts.cs

using Microsoft.EntityFrameworkCore;
using StivaRiesgos.Library.MyDbContext;

public class FirstDbContext: MyDbContext
{
    public FirstDbContext(DbContextOptions<MyDbContext> options) : base(options)
    {
    }
}

public class SecondDbContext: MyDbContext
{
    public SecondDbContext(DbContextOptions<MyDbContext> options) : base(options)
    {
    }
}

Startup.cs

public class StartUp : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.AddDbContext<FirstDbContext>(options =>
            options.UseSqlServer(ConnectionStringDbOne));

        builder.Services.AddDbContext<SecondDbContext>(options =>
            options.UseSqlServer(ConnectionStringDbTwo));

        builder.Services.AddOptions();
    }
}

Myfunction.cs

public class NotificationFunction
{
    private readonly FirstDbContext _context;
    private readonly SecondDbContext _secondcontext;

    public NotificationFunction(FirstDbContext _context, SecondDbContext _secondcontext)
    {
        this._context = _context;
        this._secondcontext = _secondcontext;
    }

    [FunctionName("NotificationFunction")]
    public async Task Run([TimerTrigger("0 0 8 * * *"){

        var querydbone = await _context.Users.Where(x => x.Active).ToListAsync(); // Returns count 0
        var querydbtwo = await _secondcontext.Users.Where(x => x.Active).ToListAsync(); // Returns count 0
    }

}

编辑

为了澄清,MyDbContext.cs 我有我的数据库的所有 mi 表和配置。我在这里工作,一切都很好,现在我必须为新环境复制这个数据库,让我们称之为 staging 并且他的连接字符串不同。 (两个数据库都在 MS Sql Server 上)。

因此,在这种情况下,我知道我已经在 MyDbContext.cs 上运行了所有实体和配置。然后,我在这里创建 CustomContext.cs 我创建了两个类(FirsDbContext.csSecondDbContext.cs)从我的基础继承并且已经在工作MyDbContext.cs,这样我就不必重新声明我在每个上下文中的所有实体或配置,然后注入 MyFunction.cs 以查询两个数据库 FirstDbContext.csSecondDbContext.cs(这里为了简单起见,真实场景是一些函数查询FirstDbContext.cs,其他函数查询SecondDbContext.cs

问题是两个上下文都没有从各自的数据库返回任何信息。而且我不知道为什么,在这种情况下也有点新手。

谢谢。

【问题讨论】:

  • 你有 MyDbContext.cs ,但你注入了 FirstDbContextSecondDbContext ?也许您创建了这些上下文但没有在此处显示它们?
  • 您遇到了什么问题?
  • 请澄清您的具体问题或提供更多详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。
  • 问题已详细更新,感谢您的时间。

标签: c# entity-framework-core azure-functions


【解决方案1】:

我们已经重现了相同的场景,并且运行良好。 在dbcontext 文件中使用以下代码和两个数据库。

示例代码:-

Azure 函数代码

using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace FunctionApp_inject_2_db_context_azure_functions_72552798
{
    public class Function1
    {
        private readonly FirstDbContext _firstcontext;
        private readonly SecondDbContext _secondcontext;
        public Function1(  SecondDbContext secondcontext, FirstDbContext _firstcontext)
        {
            this._secondcontext = secondcontext;
            this._firstcontext = _firstcontext;
        }

        [FunctionName("Function1")]
        public async Task Run([TimerTrigger("*/5 * * * * *")]TimerInfo myTimer, ILogger log)
        {
            var querydbtwo = await _secondcontext.Persons2.ToListAsync(); ; // Returns count 1
            var querydbone = await _firstcontext.Persons1.ToListAsync(); // Returns count 1
            log.LogInformation("First Db table data :- First Name :- "+ querydbone[0].FirstName.ToString()+" ,Address :- "+ querydbone[0].Address.ToString());
            log.LogInformation("Second Db table data:- First Name :- "+ querydbtwo[0].FirstName.ToString() + " ,Address : -" + querydbtwo[0].Address.ToString());
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
        }
    }
}

自定义上下文 cs 文件

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FunctionApp_inject_2_db_context_azure_functions_72552798
{
    public class FirstDbContext : DbContext
    {
        public FirstDbContext(DbContextOptions<FirstDbContext> options) : base(options)
        {
            this.ChangeTracker.LazyLoadingEnabled = false;
        }
        public virtual DbSet<Persons1> Persons1 { get; set; }
    }

    public class SecondDbContext : DbContext
    {
        public SecondDbContext(DbContextOptions<SecondDbContext> options) : base(options)
        {
            this.ChangeTracker.LazyLoadingEnabled = false;
        }
        public virtual DbSet<Persons2> Persons2 { get; set; }
    }
}

启动文件代码

using FunctionApp_inject_2_db_context_azure_functions_72552798;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;

[assembly: FunctionsStartup(typeof(StartUp))]
namespace FunctionApp_inject_2_db_context_azure_functions_72552798
{
    public class StartUp : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddDbContext<FirstDbContext>(options =>
               options.UseSqlServer("Server=xxxxx;Password=xxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"));

            builder.Services.AddDbContext<SecondDbContext>(options =>
               options.UseSqlServer("Server=xxxxx;Password=xxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"));

            builder.Services.AddOptions();
        }
    }
}

第一个数据库表

第二个数据库表

调试功能期间

输出

【讨论】:

    猜你喜欢
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    相关资源
    最近更新 更多