EF Codefirst Convert Base Class to Derived Class

别等时光非礼了梦想. 提交于 2019-12-11 08:47:19

问题


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 ?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/9467643/ef-codefirst-convert-base-class-to-derived-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!