简体   繁体   English

使用 DBContext 将 SQL 服务器数据库与时间触发的 Azure Function 连接起来

[英]Connecting SQL Server database with time-triggered Azure Function using DBContext

I am very new to Azure Functions and I am facing problems in connecting it with the SQL Server database.我对 Azure 功能非常陌生,并且在将其与 SQL 服务器数据库连接时遇到了问题。 I am using DbContext to do so.我正在使用 DbContext 这样做。

Here is my code:这是我的代码:

DbContext ( EntityContext.cs ): DbContext ( EntityContext.cs ):

public EntityContext(DbContextOptions<EntityContext> options) : base(options) { }
public DbSet<User> Users{ get; set; }

public class User
{
        public long UserId{ get; set; }
        public DateTime CreatedOn{ get; set; }
        public long CreatedBy{ get; set; }
        public DateTime ModifiedOn { get; set; }
        public long ModifiedBy { get; set; }
        public string EmailId { get; set; }
        public long PhoneNumber{ get; set; }
}

IUserRepository.cs : IUserRepository.cs

public interface IUserRepository
{
    IEnumerable<User> GetUsersData();
    User UpdateUser(User userList);
}

UserRepository.cs : UserRepository.cs

public class UserRepository: IUserRepository
{
        private readonly EntityContext context;

        public UserRepository(EntityContext context)
        {
            this.context = context;
        }

        public IEnumerable<User> GetUsersData()
        {
            var s = context.Users.Where(x => x.UserId == 123).ToList();
            return s;
        }

        public User UpdateUser(User userList)
        {
            var users = context.Users.Attach(userList);
            users.State = Microsoft.EntityFrameworkCore.EntityState.Modified;
            context.SaveChanges();
            return userList;
        }
}

Startup.cs : Startup.cs

public class Startup
{
        private IConfiguration Configuration;

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<EntityContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddScoped<IUserRepository, UserRepository>();
        }
}

local.settings.json : local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet"
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server= ;Initial Catalog=;User ID=;Password= ;MultipleActiveResultSets= True;Persist Security Info=True;"
  }
}

Function1.cs : Function1.cs

private readonly IUserRepository _irepo;

public Function1(IUserRepository irepo)
{
  _irepo = irepo;
}

[FunctionName("Function1")]
public void Run([TimerTrigger("0 15 18 * * *")]TimerInfo myTimer, ILogger log)
{
    // I have set the cron expression to 6.15 pm for the testing purpose only
    _irepo.GetUsersData();            
  
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
}

Here is the list of packages I am using:这是我正在使用的软件包列表:

Packages套餐

I have also consulted this but it didn't help me out.我也咨询过这个,但它并没有帮助我。

Also I am getting an error我也收到一个错误

Microsoft.Extensions.DependencyInjection.Abstractions: Unable to resolve service for type 'MyProject.Models.Repository.IUserRepository' while attempting to activate 'MyProject.Function1'. Microsoft.Extensions.DependencyInjection.Abstractions:尝试激活“MyProject.Function1”时无法解析“MyProject.Models.Repository.IUserRepository”类型的服务。

Somewhere I also learnt to use the package manager console to add the migrations, but I am not sure if it helps or not and I am getting the error as:在某个地方,我还学会了使用 package 管理器控制台来添加迁移,但我不确定它是否有帮助,我收到的错误如下:

EntityFramework6\Add-Migration initial

No migrations configuration type was found in the assembly 'MyProject'.在程序集“MyProject”中找不到迁移配置类型。 (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration). (在 Visual Studio 中,您可以使用 Package 管理器控制台中的 Enable-Migrations 命令添加迁移配置)。

EntityFrameworkCore\Add-Migration initial

Unable to create an object of type 'EntityContext'.无法创建“EntityContext”类型的 object。 For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728有关设计时支持的不同模式,请参阅https://go.microsoft.com/fwlink/?linkid=851728

I'm not sure what I'm doing wrong.我不确定我做错了什么。 Please suggest.请建议。

Please refer the link of the official document of Microsoft for Azure Functions. Azure功能请参考微软官方文档链接

In your case change Startup class as:在您的情况下,将Startup class 更改为:

[assembly: FunctionsStartup(typeof(MyProject.Startup))]
  namespace MyProject
  {
    public class Startup : FunctionsStartup
      {
        public override void Configure(IFunctionsHostBuilder builder)
          {
            builder.Services.AddDbContext<EntityContext>(options=> 
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            builder.Services.AddScoped<IUserRepository, UserRepository>();       
          }
      }
  }

Also in the DbContext class ( EntityContext.cs ):同样在 DbContext class ( EntityContext.cs ) 中:

public DbSet<User> User{ get; set; }
//Removed s from Users
//Also remove s from Users in the file `UserRepository.cs`

And finally in local.settings.json as:最后在local.settings.json中为:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "DefaultConnection": "Data Source= ;Initial Catalog=;User ID=;Password= ;MultipleActiveResultSets= True;Persist Security Info=True;"
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM