gpt4 book ai didi

.net - 无法实例化类 : Microsoft. EntityFrameworkCore.ChangeTracking.EntityEntry 的代理

转载 作者:行者123 更新时间:2023-12-05 09:14:59 24 4
gpt4 key购买 nike

我的存储库中有一个调用 datacontext.Add 方法并返回 resutl.Entity 的方法,例如:

 var result =  _dataContext.Product.Add(product);
await _dataContext.SaveChangesAsync();
return result.Entity;

现在我想为 EntityEntry<Product> 创建模拟但我遇到了一个异常(exception):

Message: Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry`1[[Product, Product.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]. Could not find a parameterless constructor.

这是我的测试方法代码:

 var productMock = new Mock<EntityEntry<Product>>();
var entity = new Product{Id = 1, Name = "Bag"};
mappingMock.Setup(m => m.Entity).Returns(entity);
var dataContextMock = new Mock<DataContext>(_options);
var productMockSet = new Mock<DbSet<Product>>();
dataContextMock.Setup(a => a.Product)
.Returns(productMockSet.Object);
dataContextMock.Setup(m => m.Product.Add(It.IsAny<Product>())).Returns(productMock.Object);

我做错了什么?还是有其他方法可以断言 EntityEntry?

最佳答案

我认为您缺少这些模拟对象:

var iStateManager = new Mock<IStateManager>();
var model = new Mock<Model>();

var productEntityEntry = new Mock<EntityEntry<Product>>(
new InternalShadowEntityEntry(iStateManager.Object, new EntityType("Product", model.Object, ConfigurationSource.Convention)));

productEntityEntry.SetupGet(m=> m.Entity).Returns(entity);

关于.net - 无法实例化类 : Microsoft. EntityFrameworkCore.ChangeTracking.EntityEntry 的代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53339226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com