EF (Table per Type) - Change Entity's class type

130 views Asked by At

I'm using EF 6.1 in Web API app. I'm implementing Table per Type (TPT). I followed this tutorial and everything works fine. I want to change the type of entity when updating the entity.

public abstract class BillingDetail
{
    [Key]
    public int Id { get; set; }
}

[Table("BankAccounts")]
public class BankAccount : BillingDetail
{ }

[Table("CreditCards")]
public class CreditCard : BillingDetail
{ }

I have CreditCard type entity already saved. When updating the entity, I want to save it as BankAccount type with the same primary key. Is it possible?

This is what I tried, But it throws DbUpdateConcurrencyException.

BankAccount record = ...;
record.Id = 1;  //the Id of CreditCard entity

ctx.BillingDetail.Attach(record);
ctx.Entry(record).State = EntityState.Modified;
ctx.SaveChanges(); 
1

There are 1 answers

3
Ognyan Dimitrov On

"When updating the entity, I want to save it as BankAccount type with the same primary key. Is it possible?"

If the primary key is database generated - no, because these are two separate tables in SQL and if their respected primary keys ( named Id ) are set to be database generated by incrementing the id you are violating the rule of the generation. Read the message of the exception and the message of the inner exception too - maybe there is the explanation.

Check the convention of EF for properties named Id which are int and are labeled as Key.

From Entity Framework Code First Conventions.

Code First infers that a property is a primary key if a property on a class is named “ID” (not case sensitive), or the class name followed by "ID". If the type of the primary key property is numeric or GUID it will be configured as an identity column.

Check the table schema of the SQL in order to verify this. I am almost sure the Id columns is set to be database generated by incrementation of the Id.