gpt4 book ai didi

C# Faker Bogus 生成自有属性(property)

转载 作者:行者123 更新时间:2023-12-04 17:42:56 27 4
gpt4 key购买 nike

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

最佳答案

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

Just to elaborate on why store-generated values are not supported here. The idea of having data in the model is that when the model is evolved, the seed data in the database is evolved along with it. But for that to work, each entity in the model needs to have a well-known key value such that it can be found and updated later. Feel free to use more traditional seeding mechanisms for, for example, tests that just need to initialize some data into an empty database.

关于C# Faker Bogus 生成自有属性(property),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53655941/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com