【问题标题】:Value cannot be null - In-Memory Database .Net值不能为空 - 内存数据库.Net
【发布时间】:2022-01-03 16:35:26
【问题描述】:

我正在尝试使用内存数据库,但收到以下消息:

System.ArgumentNullException: '值不能为空。 (范围 '来源')'

我阅读了很多与此问题相关的类似问题,但每篇文章都与连接字符串有关,我认为我不能使用连接字符串,因为它是内存数据库。我做错了什么?我留下我的代码:

DbInitializer.cs - 在这个类中出现错误

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

【问题讨论】:

  • public DbSet&lt;Agent&gt; AgentsRole; 在什么时候初始化?我在任何地方都看不到。如果它没有初始化,你会得到一个异常
  • 您需要做的不仅仅是“多读”。你需要fix it
  • @Charlieface 当我询问对象是否退出 DBInitializer 时,我初始化了 AgentsRole,在该行中出现错误,如果答案为 false,它将值添加到表和 AgentsRole 将不会空的,不是吗?
  • _context.AgentsRole.Any() 不会初始化它,您需要实际创建一个对象并将其存储在该变量中。请注意,@DourHighArch 上面的链接也有助于ArgumentNullException

标签: sql .net entity-framework in-memory-database


【解决方案1】:

解决方法在AppDBContext.cs中,我错过了AgentsRole的初始化,解决方法是:

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

    }
    public DbSet<Agent> AgentsRole { get; set; } // I added this Part!
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    • 2019-11-01
    • 2011-05-01
    • 2022-01-12
    • 2021-06-08
    • 2012-01-12
    • 1970-01-01
    相关资源
    最近更新 更多