Seed方法在编辑后不会第二次更新数据库。该怎么办?

时间:2019-01-20 11:48:29

标签: sql sql-server-2012 seed

我使用ASP.Net Core 2.1 MVC创建Web应用程序。要将初始数据添加到某些表中(例如,类别),我编写了Seed方法,并成功添加了Migration和更新的数据库(没有错误)。运行应用程序后,在数据库(SQL Server)中看到了数据(添加了所有值)。然后,我在种子方法中添加了其他一些类别。这次,在运行应用程序并使用迁移更新数据库后,我没有看到SQL Server中的更改(更新)。 Seed只能在第一次工作吗,还是可以使用Seed以某种方式更新(增加初始数据)数据库? 这是我的Seed方法:

 public static void Seed(OfferDbContext offerDbContext)
    {
        if (!offerDbContext.Categories.Any())
        {
            Category avto = new Category()
            {
                Name = "Avto"
            };

            Category home = new Category()
            {
                Name = "Ev"
            };

            Category digital = new Category()
            {
                Name = "Digital"
            };

            Category household = new Category()
            {
                Name = "Məişət"
            };

            Category entertainment = new Category()
            {
                Name = "Əyləncə"
            };

            Category furniture = new Category()
            {
                Name = "Mebel"
            };

            Category clothes = new Category()
            {
                Name = "Geyim"
            };

            Category cafe = new Category()
            {
                Name = "Kafe"
            };

            Category food = new Category()
            {
                Name = "Qida"
            };

            Category edu = new Category()
            {
                Name = "Təhsil"
            };

            Category medical = new Category()
            {
                Name = "Tibb"
            };

            Category tourism = new Category()
            {
                Name = "turizm"
            };

            offerDbContext.Categories.AddRange(avto, home, digital, household, entertainment, furniture, clothes, cafe, food, edu, medical, tourism);
            offerDbContext.SaveChanges(); 
        }
    }

和Program.cs中的Main方法,我将其称为“种子”:

public static void Main(string[] args)
    {
        IWebHost webHost = CreateWebHostBuilder(args).Build();

        using (IServiceScope serviceScope = webHost.Services.CreateScope())
        {
            using(OfferDbContext offerDbContext = serviceScope.ServiceProvider.GetRequiredService<OfferDbContext>())
            {           
                OfferDb.Seed(offerDbContext);
            }
        }

        webHost.Run();
    }

1 个答案:

答案 0 :(得分:0)

我认为问题在于下面的行

if (!offerDbContext.Categories.Any())

基本上,它说如果没有类别,则进行添加,否则就没有其他内容,因此,如果已经有类别,则它将什么都不做。

所以也许要添加其他内容,如果已经有类别,只需添加新的类别,

OR

可能您可以将每个创建内容包装在if中,以查看它是否已经存在,如果不存在,则将其包装。