How to set the default value for a new column of a table during First Code Migrations?

I am a little newbie to code the first migrations and it gives me a headache ...

Basically, I am trying to create a new table of values ​​("Breeds" in my example). I want to add a column to another Dogs table that contains a BreedId, cannot be null and has a default value.

After many failures, I ended up with the code below. (He did not like adding a foreign key, so I had to comment on this bit).

CreateTable( "dbo.Breeds", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false), }) .PrimaryKey(t => t.Id); Sql("SET IDENTITY_INSERT [dbo].[Breeds] ON"); Sql("INSERT into [dbo].[Breeds] ([Id], [Name]) VALUES ('1', 'Long Hair')"); Sql("SET IDENTITY_INSERT [dbo].[Breeds] OFF"); AddColumn("dbo.Dogs", "BreedId", c => c.Int(nullable: false, defaultValue: '1')); //AddForeignKey("dbo.Dogs", "BreedId", "dbo.Breeds", "Id"); CreateIndex("dbo.Dogs", "BreedId"); 

But after running Update-Database, the result is:

 ALTER TABLE [dbo].[Dogs] ADD [BreedId] [int] NOT NULL DEFAULT 49 CREATE INDEX [IX_BreedId] ON [dbo].[Dogs]([BreedId]) 

As you can see, the default value has become “49” instead of “1”, and I have no idea why. Can someone see where I'm wrong, or is there an easier way to achieve what I'm trying to do?

Thanks!

+7
sql migration ef-code-first
source share
1 answer

Sending a response via Scotch, removing quotes, then the default value is set correctly. Like this:

AddColumn ("dbo.Dogs", "BreedId", c => c.Int (nullable: false, defaultValue: 1));

+8
source share

All Articles