2016-08-12 62 views
0

實體框架6中有以下層次模型。在EntityFramework 6中將父實體更改爲子實體6

ChildUser繼承ParentUser。 ParentUser的字段少於ChildUser,我正在使用EF6的Table Per Hierarchy(TPH)繼承結構。

在某些情況下,ParentUser升級到ChildUser,那麼管理這個最好的方法是什麼?

// Naive way that doesn't work and doesn't take into account changing the discriminator 
ParentUser parentUser = ctx.ParentUsers.Single(x => x.Id == 1); 
ChildUser childUser = (ChildUser)parentUser; 
childUser.ExtraField = "Some Value"; 
ctx.SaveChanges(); 

任何指向正確方向的指針表示讚賞。

+0

你是什麼意思? – tmg

+0

對不起,我的意思是桌子。我糾正了錯字。 – Adam

回答

0

創建一個新的ChildUser對象,加上父親PARAMS和這個新的孩子「每個層級(TPH)表」添加到數據庫

ChildUser childUser = new ChildUser(); 
ParentUser parentUser = ctx.ParentUsers.Single(x => x.Id == 1); 

childUser.param1 = parentUser.param1; 
.... 
childUser.ExtraField = "Some Value"; 
ctx.ChildUsers.Add(childUser); //Add the new child 
ctx.ParentUsers.Remove(parentUser); //If you wanna remove the parent too 
ctx.SaveChanges(); 
+0

這是直接的方法,但它意味着手動複製每一個字段或使用像AutoMapper和管理與其他實體的關係(比如有一個HistoryUser表)。 – Adam

+0

@Adam當然,但只有EF纔是唯一的方法。因爲:1.您不能更改鑑別器。 2.你不能在運行時改變CLR類型,這就是你正在處理的。 –