How to change the type of the persisted class in an inherited model using the EntityFramework

Posted on

Question :

I have the following inheritance classes schema, as an example:

public class Veiculo
{
    public int Id { set; get; }
    public string Descricao { set; get; }
}

public class Moto : Veiculo { }

public class Carro : Veiculo { }

That generates the database with the Veiculo table and the columns Id , Descricao and Discriminator .

I have a record that its Discriminator field is set to Moto . That is, when I registered this record I did this using a Moto reference.

How do I transfer this record from type Moto to Carro ?

    

Answer :

Momentarily I solved it manually.

var sql = " Update Veiculo Set Discriminator = @Tipo Where Id = @Id ";

myDbContext.Database.ExecuteSqlCommand(sql,
    new SqlParameter("Tipo", "Carro"),
    new SqlParameter("Id", moto.Id));

    

Leave a Reply

Your email address will not be published. Required fields are marked *