首页 新闻 会员 周边

.NET: 如何让 AutoFixture 在生成字段值时将 int 类型字段都设置为 0

0
悬赏园豆:30 [已解决问题] 解决于 2024-01-20 22:21

场景是生成的对象需要添加到 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')
dudu的主页 dudu | 高人七级 | 园豆:30994
提问于:2024-01-20 21:31
< >
分享
最佳答案
0

只能自己实现一个 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());
dudu | 高人七级 |园豆:30994 | 2024-01-20 22:21
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册