DbContextOptions参数ASP.net核心

时间:2019-02-28 19:17:16

标签: c# asp.net-core entity-framework-core

我得到 ArgumentNullException:值不能为null。参数名称:选项 我认为这是因为我的默认构造函数使我为空,但是如果我注释掉了该构造函数,则该类的新实例将需要我不知道要提供什么的参数。帮助

 public class OvertimeRequestBusiness
    {
        public static OvertimeRequestBusiness Instance { get; } = new OvertimeRequestBusiness();
        private readonly DbContextOptions<DatabaseContext> _contextOptions;
     //default ctor
   public OvertimeRequestBusiness() : base() { }


        public OvertimeRequestBusiness(DbContextOptions<DatabaseContext> contextOptions)
        {
            _contextOptions = contextOptions;
        }
        public async Task<List<User>> GetAllUsersAsync()
        {
            using (var ctx = new DatabaseContext(_contextOptions))
            {
                var query = ctx.Users;
                var res = await query.ToListAsync();
                return res;
            }
        }
    }

在我的控制器中

  [Route("users")]
        [HttpGet]
        public async Task<List<User>> GetAllUsers()
        {
          return await OvertimeRequestBusiness.Instance.GetAllUsersAsync();
        }

1 个答案:

答案 0 :(得分:1)

以下是创建DbContextOptions的方法:

var optionsBuilder = new DbContextOptionsBuilder<DatabaseContext>();
optionsBuilder.UseSqlServer("connection_string_here");

然后DbContextOptions<DatabaseContext>将以optionsBuilder.Options的形式提供。您可以将其传递给OvertimeRequestBusiness.ctor

new OvertimeRequestBusiness(optionsBuilder.Options);