1

我想配置一个在其他直接模型上设置属性的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),
});

有没有人有想法或建议在这种情况下如何设置动态属性

4

1 回答 1

2

首先,感谢您使用Bogus

使用以下代码:

void Main()
{
   var foo = FakeFoos(1).First();
   foo.Dump();
   Console.WriteLine($"Percentage: {foo.Attributes.Percentage}");
}

选项 1 - 匿名类型

最优雅的使用方式dynamic是使用匿名类型:

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, y => new { Percentage = y.Random.Int(70, 90) });
   return config.Generate(amount);
}

在此处输入图像描述


选项 2 -ExpandoObject

更常规地,使用ExpandoObject

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, y =>
            {
               dynamic eo = new ExpandoObject();
               eo.Percentage = y.Random.Int(70, 90);
               return eo;
            });
   return config.Generate(amount);
}

在此处输入图像描述


希望对您有所帮助,如果您还有其他问题,请告诉我。:)

于 2020-05-19T03:14:13.913 回答