在EntityFramework 6中将父实体改为子实体



我在实体框架6中有以下层次结构模型。

ChildUser继承了ParentUser。ParentUser比ChildUser有更少的字段,我使用EF6的每层表(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();

任何指向正确方向的指示都是感激的。

创建一个新的ChildUser对象,添加父参数并将这个新的子对象添加到DB

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

最新更新