实体框架 - DatabaseContext不向数据库添加新行

时间:2018-01-18 20:01:22

标签: asp.net entity-framework rest

好的,所以发生了一些事情,我的初始种子突然停止了工作, 起初我的DatabaseInitializer类运行正常,这是代码:

public class DatabaseInitializer : DropCreateDatabaseIfModelChanges<DatabaseContext>
    {
        protected override void Seed(DatabaseContext context)
        {
            base.Seed(context);

            //
            context.Cities.Add(
        new Cities() { cityDesc = "London" }
        );
            context.Cities.Add(
    new Cities() { cityDesc = "Bristol" }

    );

            context.Streets.Add(
                new Streets() { cityId = 1, streetDesc = "Ab"}
                );

            context.Streets.Add(
              new Streets() { cityId = 2, streetDesc = "Cd" }
              );

            context.Streets.Add(
              new Streets() { cityId = 1, streetDesc = "Ef" }
              );

            context.Parkings.Add(
              new Parkings() { cityId = 1, streetId = 1, startDate = "2018-01-17", endDate = "2018-01-17" }
              );

            context.Parkings.Add(
          new Parkings() { cityId = 1, streetId = 2, startDate = "2019-01-17", endDate = "2019-01-17" }
          );

            context.Parkings.Add(
         new Parkings() { cityId = 2, streetId = 3, startDate = "2018-01-17", endDate = "2018-01-17" }
         );



            context.SaveChanges();
        }
    }

我的数据库有两个城市,三条街道和三个停车场。 现在,如果我添加更多停车,没有任何反应。不仅如此,即使我删除了一些停车场或街道,我仍然得到相同的JSON结果 - 两个城市,三个街道和三个停车场。 由于某种原因,种子方法停止工作,或者我的数据库被锁定&#34;。数据保持不变。

帮助?感谢

编辑:我的模特:

public class Parkings
        {
            [Key]
            public int parkId { get; set; }
            [Required]
            public string startDate { get; set; }
            [Required]
            public string endDate { get; set; }

            public int cityId { get; set; }

            [ForeignKey("cityId")]
            public virtual Cities Cities { get; set; }


            public int streetId { get; set; }



        }


        public class Cities 
        {
            [Key]
            public int cityId { get; set; }
            [Required]
            public string cityDesc { get; set; }

                  public virtual ICollection<Streets> Streets { get; set; }

                    public virtual ICollection<Parkings> Parkings { get; set; }


        }

        public class Streets
        {
            [Key]
            public int streetId { get; set; }

            public int cityId { get; set; }
            [Required]
            public string streetDesc { get; set; }

            [ForeignKey("cityId")]
           public virtual Cities Cities { get; set; }


        }

1 个答案:

答案 0 :(得分:0)

根据评论中的建议,将初始化程序设置为 DropCreateDatabaseAlways 修复了问题

相关问题