在EntityFramework 6中将父实体更改为子实体6
问题描述:
实体框架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();
任何指向正确方向的指针表示赞赏。
答
创建一个新的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类型,这就是你正在处理的。 –
你是什么意思? – tmg
对不起,我的意思是桌子。我纠正了错字。 – Adam