C# Faker Bogus generate owned property

7k Views Asked by At

I am trying to play with the Bogus library to generate random seed data in a .Net Core 2.1 application, using EF Core for data management.

I have an object called Company, which owns an Address; this is a one-to-one relationship.

Company model:

    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; }
}

Address model:

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; }
}

The seeding code available in my 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());

When running the code, I get the following exception: System.InvalidOperationException: 'The seed entity for entity type 'Company' cannot be added because there was no value provided for the required property 'RegisteredAddressId'.'

1

There are 1 best solutions below

0
On BEST ANSWER

You must specify a value for RegisteredAddressId when seeding, you cannot depend on auto-generation by your database here. See 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.