具有Table-per-type继承的实体框架模型 [英] Entity Framework Model with Table-per-Type Inheritance

查看:106
本文介绍了具有Table-per-type继承的实体框架模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在Entity Framework中定义一个具有Table-per-Type继承的模型时,如果我有一个名为person的基类/非(而不是抽象的)和两个子实体和表(成人和小孩),在创建一个子代之后,我怎么把同样的对象转换成成人?一旦转换成人,子记录应该被删除,尽管人员表中的基类数据应该保留。

解决方案

这不可能。这是类似的问题,如此处。简单的实体存在,其类型是不可变的。唯一的方法是删除子实体(=两个表中的记录)并创建一个新的成人实体(=两个表的新记录)。



看起来就像是继承的场景。



编辑:



关于继承的评论是针对您提到的场景 Person 成人儿童实体。无论如何,一旦你的情况允许改变类型,你应该考虑另一个解决方案,其中可以改变的部分将由组合处理。



例如:

  public class DataSource 
{
public int Id {get;组; }
public virtual DataSourceFeatures特征{get;组;
}

public class DataSourceFeatures
{
[Key,ForeignKey(DataSource)]
public int Id {get;组; }
public virtual DataSource DataSource {get;组; }
}

public class XmlDataSourceFeatures:DataSourceFeatures {...}

public class DelimitedDataSourceFeatures:DataSourceFeatures {...}

public class ServiceDataSourceFeatures:DataSourceFeatures {...}

现在更改类型意味着删除依赖当前 DataSourceFeatures 从数据库创建一个新的,但原始对象保持不变 - 只有关系更改。


When I define a model in Entity Framework with Table-per-Type Inheritance, if I have a base class/table (not abstract) called person, and two sub entities and tables, adult and child, after creating a child, how would I take the same object and convert it to adult? Once converted to adult, the child record should be deleted, though the base class data in the person table should be retained.

解决方案

It is not possible. It is similar problem like here. Simply the entity exists and its type is immutable. The only way to do that is delete child entity (= records from both tables) and create a new adult entity (= new records for both tables).

This doesn't look like scenario for inheritance at all.

Edit:

The comment about inheritance was targeted for scenario where you mentioned Person, Adult and Child entities. Anyway once your scenario allows changing the type you should think about another solution where the part which can change will be handled by composition.

For example:

public class DataSource
{
    public int Id { get; set; }
    public virtual DataSourceFeatures Features { get; set; }
}

public class DataSourceFeatures
{
    [Key, ForeignKey("DataSource")]
    public int Id { get; set; }
    public virtual DataSource DataSource { get; set; }
}

public class XmlDataSourceFeatures : DataSourceFeatures { ... }

public class DelimitedDataSourceFeatures : DataSourceFeatures { ... }

public class ServiceDataSourceFeatures : DataSourceFeatures { ... }

Now changing a type means deleting dependent current DataSourceFeatures from the database and create a new one but original object remains the same - only relation changes.

这篇关于具有Table-per-type继承的实体框架模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆