1

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 ?

Eray Aydogdu
  • 240
  • 1
  • 4
  • 16
  • 1
    For anyone else that comes across this question: http://stackoverflow.com/questions/12843678/converting-a-ef-codefirst-base-class-to-a-inherited-class-using-table-per-type – Brad Christie Oct 15 '13 at 14:40

2 Answers2

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.

Eranga
  • 32,181
  • 5
  • 97
  • 96
  • if i execute sql query for manually update discriminator field. Is there any occuring an exeption at runtime? – Eray Aydogdu Feb 27 '12 at 16:05
  • by the way i found this article http://blogs.msdn.com/b/jeff_adkins/archive/2004/03/15/89825.aspx and i confused – Eray Aydogdu Feb 27 '12 at 16:10
  • @ErayAydoğdu If the entity that you are going to change the type is already loaded(hence tracked) by the context you will have a problem because EF keeps track of only one instance for a given primary key value. Its better to work with a fresh context after you change the type of the entity. – Eranga Feb 27 '12 at 16:22
  • @ErayAydoğdu The like you provided shows up-casting and down-casting in C# language. These will not change the **persisted(saved)** type of the entity. – Eranga Feb 27 '12 at 16:25
  • i updated discriminator field but kisi is Kisi return true always. maybe ef working with cache. is it possible? i tried Context.Dispose() and Context.SaveChanges() – Eray Aydogdu Feb 27 '12 at 16:48
  • @ErayAydoğdu `kisi is Kisi` will always be true because its the base class. Try `kisi is Musteri`. – Eranga Feb 27 '12 at 23:32
0

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