M. Pipal
M. Pipal

Reputation: 734

EF migration - default value for string

I'm trying to update DB using EF migration (Code-First). I want to add a new string column which should contain a default value, so I create migration like this:

public override void Up()
{
    AddColumn("dbo.SupplierCodeMappings", "SupplierCompanyCode", 
                  c => c.String(defaultValueSql:"'X'"));
}

I generate a script from it, which looks also OK by my opinion.

ALTER TABLE [dbo].[SupplierCodeMappings] ADD [SupplierCompanyCode] [nvarchar](max) DEFAULT 'X'
INSERT [dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion])
VALUES (N'201709221530217_AddSupplierMappingCompanyCode', N'Ea.Data.Database.EaContext', xxxxxx , N'6.1.3-40302')

However, when I run it against the DB, the new column has NULL value for all rows. (I've also tried a variant with defaultValue:"X" in migration, without success).

I've used a default value many times before with different types (int, DateTime) and it has worked every time, is there some special behavior for strings?

Upvotes: 0

Views: 2312

Answers (1)

M. Pipal
M. Pipal

Reputation: 734

As DevilSuichiro suggested in comments, filling the default value works just when the field/column is non-nullable. I don't know if it's planned behavior but it looks like it works this way in EF/SQL now.

So this works as expected:

AddColumn("dbo.SupplierCodeMappings", "SupplierCompanyCode", 
              c => c.String(nullable: false, defaultValueSql:"'X'"));

Upvotes: 1

Related Questions