Muj
Muj

Reputation: 132

DbContextOptions parameters ASP.net core

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

Upvotes: 1

Views: 679

Answers (1)

AlbertK
AlbertK

Reputation: 13227

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

Upvotes: 2

Related Questions