EF核心无法添加实体类型“ ClientType”的种子实体,因为属性“ Id”需要非零值

时间:2019-11-11 12:09:16

标签: c# .net .net-core entity-framework-core ef-core-2.2

我正在使用EF Core 2.2.6,并且试图将一些枚举值植入表中。我有以下内容:

    var clientTypes = new List<ClientType>();
    foreach (var enumVal in Enum.GetValues(typeof(ClientTypeEnum)))
        clientTypes.Add(new ClientType { Id = (int)enumVal, Name = enumVal.ToString() });
    modelBuilder.Entity<ClientType>().HasData(clientTypes); 



public class ClientType
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    [MaxLength(128)]
    public string Name { get; set; }

    [MaxLength(512)]
    public string Description { get; set; }

    public string Icon { get; set; }
}

public enum ClientTypeEnum
{
    NewClient = 1,
    Archived = 2,
}

运行Add-Migration时出现以下错误:

EF Core The seed entity for entity type 'ClientType' cannot be added because a non-zero value is required for property 'Id'. Consider providing a negative value to avoid collisions with non-seed data.

为什么会这样?

0 个答案:

没有答案