Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the default value of a new table column during a Code-First Migrations?

I'm a bit new to code first migrations and it's giving me a headache...

Basically, I'm trying to create a new table of values ('Breeds' in my example). I want to add a column in another table 'Dogs' which holds a BreedId, cannot be null and has a default value.

After a lot of faff, I've ended up with the code below. (It didn't like the adding the foreign key so I had to comment that bit out).

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 anyone see where I'm going wrong, or is there an easier way to achieve what I'm trying to do?

Thanks!

like image 948
user2584299 Avatar asked Jul 15 '13 16:07

user2584299


1 Answers

Posting answer thanks to Scotch, removed the quotes then the default value is set correctly. Like this:

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

like image 129
user2584299 Avatar answered Sep 20 '22 13:09

user2584299