Search code examples
blazorbogusautobogus

How to generate a string guid for Bogus Faker


I'm trying to test an autocomplete component in blazor with 10,000 records generated by bogus. I keep getting the error 'Unable to case object of System.Guid to type System.String'. My class is:

public class User
{

    public string Id { get; set; } = default!;
    public string LfName { get; set; } = default!;

    public override string ToString()
    {
        return JsonSerializer.Serialize(this, new JsonSerializerOptions { WriteIndented = true     });    
    }
}

and my code is

public class DataGenerator
{
    public static readonly List<User> Users = new();
    public const int NumberOfUsers = 10000;

    public static void InitBogusData()
    {
        var userGenerator = GetUserGenerator();
        var generatedUsers = userGenerator.Generate(NumberOfUsers);
        Users.AddRange(generatedUsers);
    }


    private static Faker<User> GetUserGenerator()
    {
        return new Faker<User>()

            .RuleFor(e => e.Id, f => Guid.NewGuid().ToString())
            .RuleFor(e => e.LfName, f => f.Name.LastName() + ", " + f.Name.FirstName());
    }

    public static List<User> GetSeededEmployeesFromDb()
    {
        using var userDbContext = new UserDbContext();

        userDbContext.Database.EnsureCreated();

        var users = userDbContext.Users.ToList();

        return users;
    }
}

enter image description here

I've also just tried generating random strings as suggested in one of the suggested answers - but get the same error: .RuleFor(x => x.Id, f => f.Random.String2(1, 30))

I'm using Bogus Version 35.5.1.

Any help would be greatly appreciated


Solution

  • More likely you have a mismatch between the Id property type in the database and the Id property type in your User class. Check if the Column type of Id in your Database table is varchar or string and not uniqueidentifier. I don't think this has something to do with bogus generating fakes because you're handling that properly.