You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Bogus生成测试数据时遇Lambda转Category类型错误

问题解决:Bogus生成测试数据时Category类型不匹配错误

问题原因

你遇到的错误是因为 f.Commerce.Categories(5) 方法返回的是字符串数组(string[]),但你的 Product 类的 Category 属性是自定义的 Category 实体类型,两者无法直接转换,导致了类型不兼容的报错。

解决方案

根据你的 Category 类结构,调整 RuleFor 的逻辑,将生成的分类字符串转换成 Category 实例即可,以下是两种常见场景的实现:

场景1:从生成的多个分类中随机选一个创建Category实例

如果需要从5个随机分类里选一个作为Product的Category,且Category类包含Name属性:

var products = new Faker<Product>()
            .StrictMode(true)
            .RuleFor(e => e.Id, f => 0)
            .RuleFor(e => e.Name, (f, u) => f.Commerce.Product())
            .RuleFor(e => e.Price, (f, u) => Convert.ToDecimal(f.Commerce.Price()))
            .RuleFor(e => e.EanCode, (f, u) => f.Commerce.Ean8())
            .RuleFor(e => e.Category, (f, u) => 
                new Category 
                { 
                    Name = f.Commerce.Categories(5).Random() // 从5个分类中随机选取一个
                });

场景2:直接生成单个分类创建Category实例

如果只需要单个分类,建议使用 Commerce.Category()(单数形式,返回单个字符串),更简洁:

var products = new Faker<Product>()
            .StrictMode(true)
            .RuleFor(e => e.Id, f => 0)
            .RuleFor(e => e.Name, (f, u) => f.Commerce.Product())
            .RuleFor(e => e.Price, (f, u) => Convert.ToDecimal(f.Commerce.Price()))
            .RuleFor(e => e.EanCode, (f, u) => f.Commerce.Ean8())
            .RuleFor(e => e.Category, (f, u) => 
                new Category 
                { 
                    Name = f.Commerce.Category()
                });

补充:如果Category包含必填ID属性

如果你的Category类有Id这类必填属性,可以用Bogus的随机数生成器赋值:

.RuleFor(e => e.Category, (f, u) => 
    new Category 
    { 
        Id = f.Random.Int(1, 1000), // 生成1-1000之间的随机ID
        Name = f.Commerce.Category()
    });

内容的提问来源于stack exchange,提问作者Thomas H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 01:20:32