Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# EF Core实体类型的种子实体';ClientType';无法添加,因为属性';需要非零值;Id';_C#_.net_.net Core_Entity Framework Core_Ef Core 2.2 - Fatal编程技术网

C# EF Core实体类型的种子实体';ClientType';无法添加,因为属性';需要非零值;Id';

C# EF Core实体类型的种子实体';ClientType';无法添加,因为属性';需要非零值;Id';,c#,.net,.net-core,entity-framework-core,ef-core-2.2,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()

我正在使用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,
}
var clientTypes=new List();
foreach(Enum.GetValues中的var enumVal(typeof(ClientTypeEnum)))
Add(新的ClientType{Id=(int)enumVal,Name=enumVal.ToString()});
modelBuilder.Entity().HasData(clientTypes);
公共类ClientType
{
[关键]
[数据库生成(DatabaseGeneratedOption.Identity)]
公共int Id{get;set;}
[必需]
[MaxLength(128)]
公共字符串名称{get;set;}
[MaxLength(512)]
公共字符串说明{get;set;}
公共字符串图标{get;set;}
}
公共枚举ClientTypeEnum
{
NewClient=1,
存档=2,
}
运行
Add Migration
时,出现以下错误:

EF Core无法添加实体类型“ClientType”的种子实体,因为属性“Id”需要非零值。考虑提供一个负值以避免与非种子数据的冲突。< /代码> 


为什么会发生这种情况?

数据库生成了
Id
属性,但您正在尝试插入一个值:
clientTypes.Add(new-ClientType{Id=(int)enumVal
。尽管它可以在直接查询的某些数据库中执行,但当您使用实体框架核心时,它不能执行。必须将Id设置为
0
,才能自动生成正确的值。此外,您还可以从de DBSorry中删除
自动增量
。意外复制了粘贴的Id标识属性。将其更改为DatabaseGeneratedOption.None
且立即生效
Id
属性是DataBaseGenerated,但您正在尝试插入一个值:
clientTypes.Add(new-ClientType{Id=(int)enumVal
。尽管它可以在直接查询的某些数据库中执行,但当您使用实体框架核心时,它不能执行。必须将Id设置为
0
,才能自动生成正确的值。此外,您还可以从de DBSorry中删除
自动增量
。意外复制了粘贴的Id标识属性。将其更改为DatabaseGenerateOption.None现在可以工作了