场景是生成的对象需要添加到 EF Core 的 DbContext,如果主键字段被生成时自动赋值,SaveChanges 时就会出现下面这样的错误
The instance of entity type 'ViewCount' cannot be tracked because another instance with the key value '{EntryID: 54}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.
通过下面的代码可以将生成的 int 类型字段值控制在 0 或者 1
fixture.Customizations.Add(new RandomNumericSequenceGenerator(0, 1));
如果改成 `new RandomNumericSequenceGenerator(0, 0),会报错
System.ArgumentOutOfRangeException : Limits must be ascending numbers. (Parameter 'limits')
只能自己实现一个 ZeroGenerator
public class ZeroGenerator : ISpecimenBuilder
{
public object Create(object request, ISpecimenContext context)
{
if (!typeof(int).Equals(request))
{
return new NoSpecimen();
}
return 0;
}
}
var fixture = new Fixture();
fixture.Customizations.Add(new ZeroGenerator());