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