我可以阻止实体框架AddOrUpdate覆盖某些字段吗?

时间:2015-12-29 11:37:19

标签: c# entity-framework

我在Entity Framework迁移配置文件的种子方法中生成一些数据,如下所示:

    public void DoSeed(eVendContext context) {
        //add a test station
        context.Stations.AddOrUpdate(
          p => p.Name,
          new eVendDbDataModel.Models.Station() {
              Name = "Test Station 1",
              Active = true,
              Created = DateTime.Now,
              Modified = DateTime.Now,
              Returnable = false,
              Type = "Test",
              PortNo = "COM1",
              Parse = false,
              UseJob = true,
              UseDept = true,
              JobAlias = "Job Number",
              DeptAlias = "Department",
              SiteId = 1
          });
        context.SaveChanges();
    }

在应用程序启动时,我称之为:

        //Always update database to latest version
        Database.SetInitializer<eVendContext>(new MigrateDatabaseToLatestVersion<eVendContext, Configuration>());

然后,为了进行测试,我将直接进入数据库并将JobAlias更改为false。问题是,下次运行我的应用程序时,会调用种子方法(即使没有待处理的迁移)并更新我的数据,再次将JobAlias修复为true

有没有办法轻松停止这种行为 - 所以我可以修改我的数据库数据而不会在下次运行时被覆盖?

1 个答案:

答案 0 :(得分:3)

您可以检查此表中是否已存在任何数据,以防止其种子,如下所示:

protected override void Seed(eVendContext context) 
{

    if (!context.Stations.Any())
    {   
          context.Stations.AddOrUpdate(p => p.Name,
          new eVendDbDataModel.Models.Station() {
              Name = "Test Station 1",
              Active = true,
              Created = DateTime.Now,
              Modified = DateTime.Now,
              Returnable = false,
              Type = "Test",
              PortNo = "COM1",
              Parse = false,
              UseJob = true,
              UseDept = true,
              JobAlias = "Job Number",
              DeptAlias = "Department",
              SiteId = 1
          });

        context.SaveChanges();
    }
}