首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法添加实体类型'X‘的种子实体,因为没有为所需属性"..ID“提供的值

无法添加实体类型'X‘的种子实体,因为没有为所需属性"..ID“提供的值
EN

Stack Overflow用户
提问于 2018-04-24 20:57:15
回答 6查看 34.7K关注 0票数 21

我正在玩EF核心2.1预览2。我对HasData (Seed)方法在OnModelCreating(ModelBuilder modelBuilder)中遇到了麻烦

我的模型是简单的POCO类,没有注释。

代码语言:javascript
运行
复制
public class Tenant {
    public int TenantID {get; set;}
    public string Name {get; set;}
}

在我的DbContext内部OnModelCreating方法中,DB模型被定义为

代码语言:javascript
运行
复制
modelBuilder.Entity<Tenant>(e => {
    e.HasKey(m => m.TenantID)
     .HasName("PK_Tenants");

    e.Property(m => m.TenantID)
     .UseSqlServerIdentityColumn();

    e.Property(m => m.Name)
     .IsRequired()
     .HasMaxLength(256);
}

种子的定义是:

代码语言:javascript
运行
复制
modelBuilder.Entity<Tenant>().HasData(new []{
   new Tenant {
      TenantID = 0,
      Name = "SystemTenant",
   }
});

在ctx.Database.Migrate()运行期间,我得到了异常:不能添加实体类型‘承租者’的种子实体,因为所需的属性'TenantID没有提供值。

EN

Stack Overflow用户

发布于 2021-02-22 09:39:14

我在我的一个存储库中得到了这个错误。

代码语言:javascript
运行
复制
Exception has occurred: CLR/System.InvalidOperationException
Exception thrown: 'System.InvalidOperationException' in Microsoft.EntityFrameworkCore.dll: 
'The seed entity for entity type 'SubscriptionType'
cannot be added because a default value was provided for the required property 'Id'. 

Please provide a value different from '00000000-0000-0000-0000-000000000000'.'
       at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidateData(IModel model, IDiagnosticsLogger`1 logger)
       at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.Validate(IModel model, IDiagnosticsLogger`1 logger)
       at Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.Validate(IModel model, IDiagnosticsLogger`1 logger)
       at Microsoft.EntityFrameworkCore.SqlServer.Internal.SqlServerModelValidator.Validate(IModel model, IDiagnosticsLogger`1 logger)

问题是,我使用new Guid()将值赋值给id字段,这只是一个错误。new Guid只创建带有所有零的虚拟Guid,而Guid.NewGuid()将创建唯一的Guid。因此,我不得不在代码中使用Guid.NewGuid()

代码语言:javascript
运行
复制
builder.Entity<SubscriptionType>(b =>
            {
                b.HasKey(k => k.Id);
                b.HasData(new SubscriptionType { Id = Guid.NewGuid(), Name = "SeatBased" },
                               new SubscriptionType { Id = Guid.NewGuid(), Name = "NonSeatBased" },
                               new SubscriptionType { Id = Guid.NewGuid(), Name = "AzureEntitlement" },
                               new SubscriptionType { Id = Guid.NewGuid(), Name = "Bundle" });
            });
票数 1
EN
查看全部 6 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50010613

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档