在 Bogus 库中为 Enum 生成虚假数据
Generate fake data for Enum in Bogus library
我想用 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
class中的每个属性都有规则来生成假数据。
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
提前致谢!
答案在the documentation本身,
试试
.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>());
我想用 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
class中的每个属性都有规则来生成假数据。
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
提前致谢!
答案在the documentation本身,
试试
.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>());