DbContextOptions parameters ASP.net core

asp.net-core c# entity-framework-core

Question

I am getting ArgumentNullException: Value cannot be null. Parameter name: options I think it's because of my default constructor that I get null but If I comment out the constructor then the new instance of a class needs parameters which I don't know what to give in. HELP PLEASE

 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;
            }
        }
    }

In my controller

  [Route("users")]
        [HttpGet]
        public async Task<List<User>> GetAllUsers()
        {
          return await OvertimeRequestBusiness.Instance.GetAllUsersAsync();
        }
1
0
3/1/2019 8:05:05 AM

Accepted Answer

Here is how you can create DbContextOptions:

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

then DbContextOptions<DatabaseContext> will be available as optionsBuilder.Options. You can pass it to OvertimeRequestBusiness.ctor:

new OvertimeRequestBusiness(optionsBuilder.Options);
1
2/28/2019 7:57:27 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow