本文介绍了无法添加实体类型“X"的种子实体,因为没有为所需的属性“..ID"提供值.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩EF Core 2.1 Preview 2.我在 OnModelCreating(ModelBuilder modelBuilder)

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

My model is simple POCO class that has no annotation.

public class Tenant {
    public int TenantID {get; set;}
    public string Name {get; set;}
}

在我的 DbContext 里面的 OnModelCreating 方法是 DB 模型定义为

in my DbContext inside OnModelCreating method is DB model defined as

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);
}

种子方法定义为:

modelBuilder.Entity<Tenant>().HasData(new []{
   new Tenant {
      TenantID = 0,
      Name = "SystemTenant",
   }
});

在启动期间,当 ctx.Database.Migrate() 运行时,出现异常:无法添加实体类型租户"的种子实体,因为没有为所需的属性租户 ID"提供值


During startap, when ctx.Database.Migrate() is run, I got exception:The seed entity for entity type 'Tenant' cannot be added because there was no value provided for the required property 'TenantID

推荐答案

这个例外有点误导.内部必须有某种机制来测试所需的属性,因此它们必须与默认值不同.

The exception is little bit misleading. There must be some mechanism inside, that tests required properties so they must be different to a default values.

我唯一需要做的改变是指定 TenantID != 0.

The only change I had to do was specifying TenantID != 0.

modelBuilder.Entity<Tenant>().HasData(new []{
   new Tenant {
      TenantID = 1, // Must be != 0
      Name = "SystemTenant",
   }
});

这篇关于无法添加实体类型“X"的种子实体,因为没有为所需的属性“..ID"提供值.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 15:20