简体   繁体   English

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

[英]Change a parent entity to a child entity in EntityFramework 6

I have the following hierarchy models in Entity Framework 6. 我在实体框架6中具有以下层次结构模型。

ChildUser Inherits ParentUser. ChildUser继承ParentUser。 ParentUser has less fields than ChildUser and I am using the Table Per Hierarchy (TPH) inheritance structure of EF6. ParentUser的字段少于ChildUser的字段,我使用的是EF6的逐层表(TPH)继承结构。

In some situations the ParentUser is upgraded to ChildUser, so what is the best way to manage this? 在某些情况下,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();

Any pointers to the right directions are appreciated. 任何指向正确方向的指针都值得赞赏。

Create a new ChildUser object, add the father params and add this new child to the DB 创建一个新的ChildUser对象,添加父级参数,然后将此新子级添加到数据库中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM