2

我想用Bogus库创建假数据来测试数据库性能。这是我的书示例:

    public class Book
    {
        public Guid Id { get; set; }

        public string Title { get; set; }

        public double Price { get; set; }

        public string ISBN { get; set; }

        public Genre Genre { get; set; }
    }

    public enum Genre
    {
        Poetry,
        Romance,
        Thriller,
        Travel
    }
}

另外,我对类中的每个属性都有规则Book来生成假数据。

        public static Faker<Book> Book = new Faker<Book>()
            .StrictMode(true)
            .RuleFor(x => x.Id, f => f.Random.Guid())
            .RuleFor(x => x.Title, f => f.Company.CompanyName())
            .RuleFor(x => x.Price, f => f.Random.Double())
            .RuleFor(x => x.ISBN, f => $"ISBN_{f.Random.Guid()}")
            .RuleFor(x => x.Genre, f => ???);

我的问题是-如何为枚举生成随机值Genre

提前致谢!

4

1 回答 1

2

答案可在文档本身中找到,

尝试

.RuleFor(x => x.Genre, f =>f.PickRandom<Genre>());

你的代码看起来像,

public static Faker<Book> Book = new Faker<Book>()
        .StrictMode(true)
        .RuleFor(x => x.Id, f => f.Random.Guid())
        .RuleFor(x => x.Title, f => f.Company.CompanyName())
        .RuleFor(x => x.Price, f => f.Random.Double())
        .RuleFor(x => x.ISBN, f => $"ISBN_{f.Random.Guid()}")
        .RuleFor(x => x.Genre, f => f.PickRandom<Genre>());

POC:.NET 小提琴

于 2021-06-28T18:06:37.037 回答