EF Core 2.1种子数据主键

时间:2018-09-13 02:25:30

标签: entity-framework-core ef-migrations ef-core-2.1

我刚遇到一个问题,让人想起鸡肉和鸡蛋的情况。

我正在尝试在EF 2.1.3中播种数据。我有一堂课叫做“样本”。

public class Sample
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public bool IsActive { get; set; }
        public bool IsVisible { get; set; }
    }

我有以下种子方法:

builder.HasData(
                new Sample {Id=1, IsActive = true, IsVisible = true, Name = "Test 1" },
                new Sample { Id = 2, IsActive = true, IsVisible = true, Name = "Test 2" },
                new Sample { Id = 3, IsActive = true, IsVisible = true, Name = "Test 3" }
                );

现在,这似乎在我第一次生成迁移文件时就可以了

现在,但是,每次我运行“添加迁移”命令时,都会出现此错误:

The seed entity for entity type 'Sample' cannot be added because another seed entity with the same key value for {'Id'} has already been added. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

从种子数据中删除Id值-导致此错误:

The seed entity for entity type 'Sample' cannot be added because there was no value provided for the required property 'Id'.

1 个答案:

答案 0 :(得分:0)

这是以前添加的ID。您要插入重复的键值。