我正在玩EF核心2.1预览2。我对HasData (Seed)方法在OnModelCreating(ModelBuilder modelBuilder)
中遇到了麻烦
我的模型是简单的POCO类,没有注释。
public class Tenant {
public int TenantID {get; set;}
public string Name {get; set;}
}
在我的DbContext
内部OnModelCreating
方法中,DB模型被定义为
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()运行期间,我得到了异常:不能添加实体类型‘承租者’的种子实体,因为所需的属性'TenantID没有提供值。
发布于 2021-02-22 09:39:14
我在我的一个存储库中得到了这个错误。
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()
。
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" });
});
https://stackoverflow.com/questions/50010613
复制相似问题