Reputation: 151
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!
Upvotes: 7
Views: 1328
Reputation: 151
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));
Upvotes: 8