Search code examples
entity-frameworkef-code-firstdatabase-restoretable-per-hierarchydiscriminator

EF6 code-first Discriminator from Backupfile


I have a backup file of an old database where I havn't used EF. Now I create a new database with EF code first fluent api with table per hierachy. That's why I have a not-nullable discriminator column. In my backup file there is no discriminator. So when I try to restore my old backup file an exception is thrown because of trying to insert a NULL value into the discriminator column.

Is it possible to set a default value (with help of the EF) when inserting NULL into the discriminator column?

Edit: The restore is done with help of datasets. I could add the value into the dataset but I don't want to do it like that.


Solution

  • You can create your database with EF. Then you run the following SQL command:

    context.Database.ExecuteSqlCommand("ALTER Table dbo.TABLENAME DROP COLUMN Discriminator");
    

    Afterwards you can run your restore. Finally you add the Discriminator by hand:

    context.Database.ExecuteSqlCommand("ALTER Table dbo. TABLENAME ADD
    Discriminator NVARCHAR(128) NOT NULL DEFAULT 'ClassName'");
    

    If you have Table Per Hierachy with multiple types then you might need some sort of post-processing to set the correct type ind the Discriminator field.