简体   繁体   中英

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?

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'"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM