ApplicationDbContext对象引用未设置为对象的实例

时间:2018-07-30 01:48:48

标签: asp.net-mvc sqlite dbcontext

我正在尝试使用ASP.Net Core MVC应用将数据播种到我的Sqlite数据库中。一切正常,直到命令:

context.SaveChanges()

触发此操作后,尽管事先已将其添加到上下文中而没有问题,但会引发“未将引用设置为对象的实例”。这是可疑代码:

public class Seeder
    {
        private ApplicationDbContext context;
        public Seeder(ApplicationDbContext _context)
        {
            context = _context;
        }
        //populate the database with the static items
        public void SeedData()
        {
            //jump out if data already exists
            if(context.HomeTypes.Count() != 0)
            {
                return;
            }

            //build the home types
            HomeType basic = new HomeType
            {
                home_type_id = 0,
                name = "Town House",
                capacity = 2,
                home_image_src = "changeThisLater"
            };
            context.HomeTypes.Add(basic);

            context.SaveChanges();

        }
    }

在此处称为种子类:

public static void Main(string[] args)
        {
            var host = BuildWebHost(args);

            //seed the database when the app starts up
            using(var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var context = services.GetRequiredService<ApplicationDbContext>();
                    Seeder seeder = new Seeder(context);
                    seeder.SeedData();
                }catch(Exception e)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(e, "An error occured while seeding the db");
                }
            }

            //run
            host.Run();

        }

这是我的错误消息的照片:

1 个答案:

答案 0 :(得分:1)

已解决!

问题出在我的身份证上。在此播种器中,我将home_type_id的值设置为0。EF Core自动生成ID,因此这引起了问题,并将我的ID添加为-2175267(或类似的东西)。

解决方法只是添加:

 //prevent auto generation of the id feilds
 builder.Entity<Role>().Property(m => m.role_id).ValueGeneratedNever();
 builder.Entity<HomeType>().Property(m => m.home_type_id).ValueGeneratedNever();

到OnModelCreating函数中的ApplicationDbContext,它现在可以正常工作

相关问题