我想配置一个在其他直接模型上设置属性的Bogus规则。dynamic
注意我知道这通常与 C# 编译器/运行时非常相关,并且非常欢迎在这种情况下提供解决方案。但是,如果有的话,我也将不胜感激 Bogus-specific 解决方案。
public class Foo
{
public string Id { get; set; }
public dynamic Attributes { get; set; }
}
使用 Bogus 库我想配置一个 Faker 规则,如下所示:
public static IReadOnlyCollection<Foo> FakeFoos(int amount)
{
var config = new Faker<Foo>()
.StrictMode(false)
.RuleFor(x => x.Id, y => y.Random.Guid().ToString("N"))
.RuleFor(x => x.Attributes.......) // <-- this here
return config.Generate(amount);
}
假设我想设置foo.Attributes.Percentage
为整数。我尝试了几种方法,都导致 dotnetcore 3.1 出现不同的错误。
示例 1:
// Error [CS1963] An expression tree may not contain a dynamic operation
.RuleFor(x => x.Attributes.Percentage, y => y.Random.Int(70, 90))
示例 2:
// Error System.ArgumentException : Your expression '(x.Attributes As SomeWrappingClass).Percentage' cant be used.
// Nested accessors like 'o => o.NestedO...
.RuleFor(x => (x.Attributes as SomeWrappingClass).Percentage, y => y.Random.Int(70, 90))
示例 3:
// Error RuntimeBinderException : Cannot perform runtime binding on a null reference
.RuleFor(x => x.Attributes, y => new SomeWrappingClass
{
Percentage = y.Random.Int(70, 90),
});
有没有人有想法或建议在这种情况下如何设置动态属性?