问题
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