【发布时间】: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.cs 和 SecondDbContext.cs)从我的基础继承并且已经在工作MyDbContext.cs,这样我就不必重新声明我在每个上下文中的所有实体或配置,然后注入 MyFunction.cs 以查询两个数据库 FirstDbContext.cs 或 SecondDbContext.cs(这里为了简单起见,真实场景是一些函数查询FirstDbContext.cs,其他函数查询SecondDbContext.cs
问题是两个上下文都没有从各自的数据库返回任何信息。而且我不知道为什么,在这种情况下也有点新手。
谢谢。
【问题讨论】:
-
你有
MyDbContext.cs,但你注入了FirstDbContext和SecondDbContext?也许您创建了这些上下文但没有在此处显示它们? -
您遇到了什么问题?
-
请澄清您的具体问题或提供更多详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。
-
问题已详细更新,感谢您的时间。
标签: c# entity-framework-core azure-functions