简体   繁体   中英

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.

I saved a Kisi and this could be in relation to other tables. How can I cast/convert/"promote" it to a Musteri, keeping the same ID ? I can't recreate.

I could issue a "manual" SQL INSERT, but it's kind of ugly...

How can i handle it without loosing the KisiID ?

This is not possible without bypassing the abstraction of EF. EF does not allow you to change the entity type at runtime. The discriminator column is not exposed by EF.

What you can do is manually update the corresponding row using a SQL Update statement.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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