【问题标题】:Database (Ef) connection from Azure Function来自 Azure Function 的数据库 (Ef) 连接
【发布时间】:2022-06-10 19:27:25
【问题描述】:

所以我有一个 Azure 函数应用程序,我想从那里连接到数据库。我为此使用依赖注入并创建服务,但我无法连接到数据库。我将展示我的一些代码。

public class Program
    {
        public static void Main()
        {
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
            var host = new HostBuilder()
                .ConfigureFunctionsWorkerDefaults()
                .ConfigureServices(s =>
                {
                    s.AddDbContext<MyDbContext>(o =>
                        o.UseSqlServer("database_connection"));
                   
                })
                .Build();

            host.Run();
        }

    }

这是我的 Azure Function 项目中的代码。这是我的功能项目的包

    <PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
    <PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.0.13" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.ServiceBus" Version="4.2.1" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.3.0" OutputItemType="Analyzer" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.6.0" />

现在我有另一个项目,我的数据层,其中有我的 MyDbContext。这是这个的代码

public partial class MyDbContext: DbContext
    {
        public static String connString = null;

        public MyDbContext() { }

        public MyDbContext(DbContextOptions<MyDbContext> options)
            : base(options)
        {
            var opt = options.FindExtension<SqlServerOptionsExtension>();
            connString = opt.ConnectionString;

        }

        public static MyDbContextGetNewInstance()
        {
            var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
            optionsBuilder.EnableSensitiveDataLogging();
            optionsBuilder.UseSqlServer(connString);
            return new MyDbContext(optionsBuilder.Options);
        }
}

我的 api 项目中有相同的代码,并且与数据库的连接工作正常。但从我的天蓝色功能来看,它没有。我的经验是,如果我在我的 azure 函数的构造函数中设置一个断点,它不会被调用,那就是我的 connString 为空。

我错过了什么吗?

【问题讨论】:

标签: azure entity-framework asp.net-core dependency-injection azure-functions


【解决方案1】:

我错过了什么吗?

是的,尝试从MyDbContext 中删除您的默认构造函数。

使用以下示例和工作代码将azure function 连接到使用EF 的数据库。

第 1 步:-Startup 文件中使用以下代码。

using FunctionApp_Connect_db_context_azure_functions;
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<MyDbContext>(options =>
               options.UseSqlServer("Server=tcp:xxx;User ID=adminserverdb1;Password=xxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"));

            builder.Services.AddOptions();
        }
    }
}

Setp 2 :- 添加DB context 文件并使用以下代码

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

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

第 3 步:- 创建 Azure function 并使用以下代码。

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_Connect_db_context_azure_functions
{
    public class Function1
    {
        private readonly MyDbContext _myDbcontext;
        
        public Function1(MyDbContext mydbcontext)
        {
            this._myDbcontext = mydbcontext;
        }

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

数据库

输出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    相关资源
    最近更新 更多