EF 6代码初始化数据库中的第一个更新表

时间:2017-05-04 16:06:54

标签: c# entity-framework code-first

我正在使用EF 6和代码。我已经有一个操作数据库,我再添加一个表(table2),将1xN与其他表(table1)相关联。 在initializeDatabase(context)中,我在新表(table2)中添加了一条记录。问题是:如何使用FK更新table1的所有记录,并将最近插入的记录的id更新为table2。如果我什么都不做,fk字段更新为NULL,但我想用插入记录的id更新。

我在这里插入新表:

public override void InitializeDatabase(AppContext context)
{
   var storeTypes = context.StoreTypes.FirstOrDefault();
   if (storeTypes != null) return;
   context.StoreTypes.Add(new StoreType { Name = "Local", Description = "Local" });
   context.StoreTypes.Add(new StoreType { Name = "Gondola", Description = "Gondola" });
   context.SaveChanges();
}

1 个答案:

答案 0 :(得分:0)

好的,我无法从您的问题中确切地告诉您正在处理哪些表,所以我假设StoreTypes是主表中的查找表和存储?我不习惯在InitializeDatabase中看到Seed()代码,但我认为这样可行。

public override void InitializeDatabase(AppContext context)
{

   if (!context.StoreTypes.Any(st => st.Name == "Local"))
   {
       var newStoreType = new StoreType { Name = "Local", Description = "Local" };
       context.SaveChanges();  // newStoreType will now have id
       var storesToUpdate = context.Stores.Where(s => s.StoreTypeId == 0);
       storesToUpdate.ForEach(s => s.StoreTypeId = newStoreType.Id);
       context.SaveChanges();
   }
}