C# 使用DBContext将SQL Server数据库与时间触发的Azure函数连接

C# 使用DBContext将SQL Server数据库与时间触发的Azure函数连接,c#,entity-framework,.net-core,azure-functions,dbcontext,C#,Entity Framework,.net Core,Azure Functions,Dbcontext,我对Azure功能非常陌生,在将其与SQL Server数据库连接时遇到了问题。我正在使用DbContext来实现这一点 这是我的密码: DbContext(EntityContext.cs): UserRepository.cs: public EntityContext(DbContextOptions<EntityContext> options) : base(options) { } public DbSet<User> Users{ get; set; }

我对Azure功能非常陌生,在将其与SQL Server数据库连接时遇到了问题。我正在使用DbContext来实现这一点

这是我的密码:

DbContext
EntityContext.cs
):

UserRepository.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; }
}
public interface IUserRepository
{
    IEnumerable<User> GetUsersData();
    User UpdateUser(User userList);
}
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;
        }
}
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>();
        }
}
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}");
}
public DbSet<User> User{ get; set; }
//Removed s from Users
//Also remove s from Users in the file `UserRepository.cs`
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

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; }
}
public interface IUserRepository
{
    IEnumerable<User> GetUsersData();
    User UpdateUser(User userList);
}
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;
        }
}
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>();
        }
}
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}");
}
public DbSet<User> User{ get; set; }
//Removed s from Users
//Also remove s from Users in the file `UserRepository.cs`
以下是我正在使用的软件包列表:

我也咨询过,但没有帮到我

我也得到了一个错误

Microsoft.Extensions.DependencyInjection.Abstractions:在尝试激活“MyProject.Function1”时,无法解析类型“MyProject.Models.Repository.IUserRepository”的服务

在某个地方,我还学会了使用package manager控制台添加迁移,但我不确定它是否有用,我得到的错误如下:

EntityFramework6\Add-Migration initial
在程序集“MyProject”中未找到迁移配置类型。(在Visual Studio中,您可以从Package Manager控制台使用Enable Migrations命令添加迁移配置)

无法创建“EntityContext”类型的对象。有关设计时支持的不同模式,请参见

我不确定我做错了什么。请提供建议。

有关Azure功能,请参阅Microsoft官方文档的

在您的情况下,将
启动
类更改为:

[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>();       
          }
      }
  }
最后在
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;"
  }
}

您应该使用
services.AddDbContext
而不是
services.AddDbContext
这是一个错误,对此我深表歉意。我已经改正了