也許這個鏈接可以幫助你 EF Code First - Cannot insert the value NULL into column
這裏是鏈接代碼,這將可以幫助你:
我造成了通過應用遷移到現有 數據庫類似的問題,所以我創建一個空的遷移和使用SQL代碼,這裏是我的 例子:
public override void Up()
{
DropForeignKey("dbo.Bar", "FooId", "dbo.Foo");
Sql("IF object_id(N'[dbo].[FK_Bar_Foo]', N'F') IS NOT NULL ALTER TABLE [dbo].[Bar] DROP CONSTRAINT [FK_Bar_Foo]");
Sql("CREATE TABLE [dbo].[FooTemp] ([Id] int NOT NULL)");
Sql("INSERT INTO [dbo].[FooTemp] ([Id]) SELECT [Id] FROM [dbo].[Foo]");
Sql("DROP TABLE [dbo].[Foo]");
Sql("CREATE TABLE [dbo].[Foo] ([Id] int IDENTITY (1,1) NOT NULL)");
Sql("SET IDENTITY_INSERT [dbo].[Foo] ON");
Sql("INSERT INTO [dbo].[Foo] ([Id]) SELECT [Id] FROM [dbo].[FooTemp]");
Sql("SET IDENTITY_INSERT [dbo].[Foo] OFF");
Sql("DROP TABLE [dbo].[FooTemp]");
AddPrimaryKey("dbo.Foo", "Id");
AddForeignKey("dbo.Bar", "FooId", "dbo.Foo", "Id");
}
public override void Down()
{
DropForeignKey("dbo.Bar", "FooId", "dbo.Foo");
Sql("CREATE TABLE [dbo].[FooTemp] ([Id] int NOT NULL)");
Sql("INSERT INTO [dbo].[FooTemp] ([Id]) SELECT [Id] FROM [dbo].[Foo]");
Sql("DROP TABLE [dbo].[Foo]");
Sql("CREATE TABLE [dbo].[Foo] ([Id] int NOT NULL)");
Sql("INSERT INTO [dbo].[Foo] ([Id]) SELECT [Id] FROM [dbo].[FooTemp]");
Sql("DROP TABLE [dbo].[FooTemp]");
AddPrimaryKey("dbo.Foo", "Id");
AddForeignKey("dbo.Bar", "FooId", "dbo.Foo", "Id");
}