我正在尝试使用 Bogus 库在 .Net Core 2.1 应用程序中生成随机种子数据,使用 EF Core 进行数据管理。
我有一个名为 Company 的对象,它拥有一个地址;这是一对一的关系。
公司型号:
public class Company
{
public long Id { get; set; }
[Required]
public Address Address { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string Website { get; set; }
}
地址型号:
public class Address : IValidatableObject
{
public long Id { get; set; }
public string Street1 { get; set; }
public string Street2 { get; set; }
public string ZipCode { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
我的 DbContext 中可用的种子代码:
var TestAddresses = new Faker<Address>()
.RuleFor(o => o.Id, f => aId++)
.RuleFor(o => o.Street1, f => f.Address.StreetAddress(true))
.RuleFor(o => o.Country, f => f.Address.Country())
.RuleFor(o => o.City, f => f.Address.City());
var c = new Faker<Company>()
.RuleFor(o => o.Id, f => f.IndexFaker+1)
.RuleFor(o => o.RegisteredAddress, f => TestAddresses.Generate())
.RuleFor(o => o.Phone, f => f.Phone.ToString())
.RuleFor(o => o.Email, f => f.Internet.Email())
.FinishWith((f, u) =>
{
Console.WriteLine("Company created! Id = {0}", u.Id);
});
b.Entity<Company>().HasData(c.Generate(100).ToArray());
运行代码时,出现以下异常: System.InvalidOperationException: '无法添加实体类型 'Company' 的种子实体,因为没有为所需属性 'RegisteredAddressId' 提供值。