【问题标题】:C# Faker Bogus generate owned propertyC# Faker Bogus 生成拥有的财产
【发布时间】:2019-05-08 10:01:47
【问题描述】:

我正在尝试使用 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'提供值。'

【问题讨论】:

    标签: c# entity-framework-core bogus


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-12-09
      • 1970-01-01
      • 2011-02-23
      • 2021-04-29
      • 2021-06-01
      • 2023-04-07
      • 1970-01-01
      • 2021-07-08
      • 2020-05-24
      相关资源
      最近更新 更多