0

I am trying to use a In-Memory Database, but I get this message:

System.ArgumentNullException: 'Value cannot be null. (Parameter 'source')'

I read a lot some similar question related with this issue, but every article is related with the connection String, and I think I must not use a ConnectionString because is a In-Memory Database. What Do I do wrong? I leave my code:

DbInitializer.cs - In this class appears the error

public static class DbInitializer
{
    public static void Initialize(IServiceProvider serviceProvider)
    {
        using (var _context = new AppDBContext(serviceProvider.GetRequiredService<DbContextOptions<AppDBContext>>()))
        {
            if (_context.AgentsRole.Any()) //In this line appears the error
                return;
            _context.AgentsRole.AddRange(
                    new Agent { Id = 1, Role_Name = "David Lopez", Is_Active = true, Role_Description = "This is a test for David Lopez" },
                    new Agent { Id = 2, Role_Name = "James Norris", Is_Active = false, Role_Description = "This is a test for James Norris" },
                    new Agent { Id = 3, Role_Name = "Jhon Norris", Is_Active = true, Role_Description = "This is a test for Jhon Norris" },
                    new Agent { Id = 4, Role_Name = "James Norr", Is_Active = true, Role_Description = "This is a test for James Norr" }
                );
            _context.SaveChanges();
        }
    }
}

Startup.cs:

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

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<AppDBContext>(options=> options.UseInMemoryDatabase(databaseName: "InMemory_DB"));
            services.AddControllers();
            services.AddSwaggerGen();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My Test1 Api v1");
            });
        }
    }

Program.cs:

public class Program
    {
        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                var context = services.GetRequiredService<AppDBContext>();
                DbInitializer.Initialize(services);
            }
            host.Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

Controller.cs:

[ApiController]
[Route("api/[controller]")]
public class AgentRoleController : ControllerBase
{
    private readonly ILogger<AgentRoleController> _logger;
    private readonly AppDBContext _context;
    public AgentRoleController(ILogger<AgentRoleController> logger, AppDBContext context)
    {
        _logger = logger;
        _context = context;
    }
    [HttpGet]
    [SwaggerOperation("GetAgentsRole")]
    [SwaggerResponse((int)HttpStatusCode.OK)]
    [SwaggerResponse((int)HttpStatusCode.NotFound)]
    public IEnumerable<Agent> Get()
    {
        return _context.AgentsRole;
    }
}

AppDBContext.cs:

public class AppDBContext : DbContext
{
    public AppDBContext(DbContextOptions<AppDBContext> options)
        :base(options)
    {
       
    }
    public DbSet<Agent> AgentsRole;
}
vvvvv
  • 25,404
  • 19
  • 49
  • 81
Fabian Rico
  • 69
  • 2
  • 8
  • `public DbSet AgentsRole;` at what point does this get initialized? I can't see that anywhere. If it's not initialized you will get an exception – Charlieface Jan 03 '22 at 16:46
  • 1
    You need to do more than just “read a lot”. You need to [fix it](https://stackoverflow.com/questions/4660142/). – Dour High Arch Jan 03 '22 at 17:03
  • @Charlieface I initialize the AgentsRole when I ask to the object if exit any in DBInitializer, in the line appears the error, if the answer is false, It add values to the Table and AgentsRole will not be empty, is it not? – Fabian Rico Jan 03 '22 at 17:50
  • `_context.AgentsRole.Any()` does not initialize it, you need to actually create an object and store it in that variable. Note that the link above by @DourHighArch also helps for `ArgumentNullException` – Charlieface Jan 03 '22 at 17:51

1 Answers1

0

The solution is in AppDBContext.cs, I missed the initialization of AgentsRole, the solution is:

public class AppDBContext : DbContext
{
    public AppDBContext(DbContextOptions<AppDBContext> options)
        :base(options)
    {

    }
    public DbSet<Agent> AgentsRole { get; set; } // I added this Part!
}
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
Fabian Rico
  • 69
  • 2
  • 8