我先使用EF代码 DomesticTask类看起来像
public class DomesticTask
{
public int Id { get; set; }
[Required]
public ApplicationUser DomesticClient { get; set; }
public DateTime DateTime { get; set; }
[Required]
[StringLength(500)]
public string Description { get; set; }
[Required]
public Category Category { get; set; }
}
类别类正在关注
{
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
}
数据库上下文正在关注
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<DomesticTask> DomesticTasks { get; set; }
public DbSet<Category> Categories { get; set; }
我的迁移类看起来像这样
public partial class PopulateCategoriesTable : DbMigration
{
public override void Up()
{
Sql("INSERT INTO Categories (Id, Name) VALUES (1, 'Plumber')");
Sql("INSERT INTO Categories (Id, Name) VALUES (2, 'Mason')");
Sql("INSERT INTO Categories (Id, Name) VALUES (3, 'Labour')");
Sql("INSERT INTO Categories (Id, Name) VALUES (4, 'Milk-man')");
Sql("INSERT INTO Categories (Id, Name) VALUES (5, 'Electrician')");
}
public override void Down()
{
Sql("DELETE FROM Categories WHERE Id IN (1, 2, 3, 4, 5)");
}
}
当我执行update-database时,它会显示以下错误。
错误号:544,状态:1,类:16无法为其插入显式值 表格中的标识列&#39;类别&#39;当IDENTITY_INSERT设置为 OFF。
如何解决错误?
答案 0 :(得分:0)
您正在插入作为标识列的类别的Id的值,它应该由sql server插入。
答案 1 :(得分:0)
您应该更新迁移脚本,以便在插入时设置identity
列值。我当然假设您使用SQL Server作为数据存储,因为以下代码使用的是T-SQL而不是ANSI-92 SQL。
public partial class Seed_Categories : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(@"
SET IDENTITY_INSERT [dbo].[Categories] ON;
INSERT INTO [dbo].[Categories] ([ID], [NAME], [CODE])
VALUES
(1, 'Science Fiction', 'SCIFI'),
(2, 'Historical Fiction', 'HISFI'),
(3, 'Historical', 'HISTO'),
(4, 'English Literature', 'ENGLT'),
(5, 'Spanish Literature', 'SPALT');
SET IDENTITY_INSERT [dbo].[Categories] OFF;
");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}