2017-05-04 80 views
0

我使用EF 6和代碼優先。我已經有了一個可操作的數據庫,我添加了一個表(表2),與其他表(table1)關聯1xN。 在initializeDatabase(上下文)中,我向新表(table2)中添加了一條記錄。問題是:我如何用FK更新table1的所有記錄,並將最近插入的記錄的id更新到table2中。如果我什麼都不做,fk字段更新爲NULL,但我想更新插入記錄的ID。EF 6代碼初始化數據庫中的第一個更新表

我在這裏插入新表:

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(); 
} 

回答

0

OK,我真的不能從你的問題是什麼表,你正在處理知道,所以我會假設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(); 
    } 
} 
相關問題