C# Faker Bogus 生成拥有的财产

pab*_*pab 5 c# entity-framework-core bogus

我正在尝试使用 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; }
}
Run Code Online (Sandbox Code Playgroud)

地址型号:

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; }
}
Run Code Online (Sandbox Code Playgroud)

我的 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());
Run Code Online (Sandbox Code Playgroud)

运行代码时,出现以下异常: System.InvalidOperationException:“无法添加实体类型“Company”的种子实体,因为没有为所需属性“RegisteredAddressId”提供值。”

use*_*702 1

您必须在播种时指定一个值RegisteredAddressId,不能依赖数据库自动生成。请参阅https://github.com/aspnet/EntityFrameworkCore/issues/11776#issuecomment-383756228

只是为了详细说明为什么此处不支持商店生成的值。在模型中包含数据的想法是,当模型演化时,数据库中的种子数据也随之演化。但为了使其发挥作用,模型中的每个实体都需要有一个众所周知的键值,以便以后可以找到并更新它。可以随意使用更传统的播种机制,例如,只需要将一些数据初始化到空数据库中的测试。