本文介绍了无法添加实体类型“ X”的种子实体,因为没有为必需的属性“ ..ID”提供值。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在玩 EF Core 2.1 Preview 2 。 我在 OnModelCreating(ModelBuilder modelBuilder) 我的模型是public class Tenant { public int TenantID {get; set;} public string Name {get; set;}}在我的 DbContext OnModelCreating 方法内的$ c>是定义为in my DbContext inside OnModelCreating method is DB model defined asmodelBuilder.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()时,出现异常:无法添加实体类型 Tenant的种子实体,因为存在没有为必需的属性'TenantID 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”提供值。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-21 17:10