gpt4 book ai didi

c# - 最小起订量 - 设置 在哪里扩展?

转载 作者:太空宇宙 更新时间:2023-11-03 19:50:57 24 4
gpt4 key购买 nike

如何在对象上设置 where linq 扩展? DbSet就我而言。这是我的代码:

this.workflowStateSet
.Setup(m => m.Where(It.IsAny<Expression<Func<Model.WorkflowState, int, bool>>>()))
.Returns(new List<Model.WorkflowState>().AsQueryable());

但是,它给了我一个不太熟悉的异常:

System.NotSupportedException: Expression references a method that does not belong to the mocked object: m => m.Where<WorkflowState>

如有任何提示,我将不胜感激。

最佳答案

这个扩展方法将有助于模拟 DbSet

public static class MockDbSetExtensions {
public static Mock<DbSet<T>> AsDbSetMock<T>(this IEnumerable<T> list) where T : class {
IQueryable<T> queryableList = list.AsQueryable();
Mock<DbSet<T>> dbSetMock = new Mock<DbSet<T>>();
dbSetMock.As<IQueryable<T>>().Setup(x => x.Provider).Returns(queryableList.Provider);
dbSetMock.As<IQueryable<T>>().Setup(x => x.Expression).Returns(queryableList.Expression);
dbSetMock.As<IQueryable<T>>().Setup(x => x.ElementType).Returns(queryableList.ElementType);
dbSetMock.As<IQueryable<T>>().Setup(x => x.GetEnumerator()).Returns(() => queryableList.GetEnumerator());
return dbSetMock;
}
}

你可以像这样使用它。

//Arrange
var data = new List<Model.WorkflowState>();
//you would populate your list as needed.
//convert it to a mock DbSet that uses the list as its datasource
var workflowStateSet = data.AsDbSetMock();
var dbSet = workflowStateSet.Object;

//Act
var items = dbSet.Where("Your expression here");

//Assert
//....

关于c# - 最小起订量 - 设置 在哪里扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39574617/

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