简体   繁体   English

EF Codefirst将基类转换为派生类

[英]EF Codefirst Convert Base Class to Derived Class

Supposing the following entities : 假设以下实体:

public class Kisi
{
    [Key]
    public int KisiID { get; set; }
    public string Ad { get; set; }
    public string Soyad { get; set; }

    public virtual ICollection<Grup> Gruplar { get; set; }
    public virtual ICollection<Kampanya> Kampanyalar { get; set; }
}

public class Musteri : Kisi
{
    public int? Yas { get; set; }
    public string Meslek { get; set; }

}

These two classes storing one table(TPH) in SQL SERVER. 这两个类在SQL SERVER中存储一个表(TPH)。

I saved a Kisi and this could be in relation to other tables. 我保存了一个Kisi,这可能与其他表有关。 How can I cast/convert/"promote" it to a Musteri, keeping the same ID ? 我如何在保留相同ID的情况下将其转换/转换/“升级”为Musteri? I can't recreate. 我无法重建。

I could issue a "manual" SQL INSERT, but it's kind of ugly... 我可以发出“手动” SQL INSERT,但这有点丑陋...

How can i handle it without loosing the KisiID ? 我如何在不失去KisiID的情况下进行处理?

This is not possible without bypassing the abstraction of EF. 如果不绕过EF的抽象,这是不可能的。 EF does not allow you to change the entity type at runtime. EF不允许您在运行时更改实体类型。 The discriminator column is not exposed by EF. 鉴别符列未通过EF公开。

What you can do is manually update the corresponding row using a SQL Update statement. 您可以做的是使用SQL Update语句手动更新相应的行。

Try this: 尝试这个:

var kisi=context.Kisi.Find(Id);
context.Entry(kisi).State=EntityState.Deleted;
var musteri= new Musteri()
{
    KisiID=kisi.KisiID,
    Ad=kisi.Ad,
    Soyad=kisi.Soyad,
    Gruplar= kisi.Gruplar,
    Kampanyalar=kisi.Kampanyalar,
    Meslek="Adaskdm"
}
context.Entry(musteri).State=EntityState.Added;
context.SaveChanges();

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

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