问题描述
我有一个通用存储库,正在尝试转换.Returns为Expression,但是它拒绝...我的代码如下:
I have a Generic repository and are trying to cast the .Returns to a Expression but it refuse... My code is following:
public RepositoryTest()
{
IList<MockObjectSet> mocks = new List<MockObjectSet>()
{
new MockObjectSet { FirstName = "Beta", LastName = "Alpha", Mobile = 12345678 },
new MockObjectSet { FirstName = "Alpha", LastName = "Beta", Mobile = 87654321 }
};
var mockRepository = new Mock<IRepository<MockObjectSet>>();
mockRepository.Setup(x => x.GetBy(It.IsAny<Expression<Func<MockObjectSet, bool>>>()))
.Returns((Expression<Func<MockObjectSet, bool>> predicate) => mocks.Where(predicate).ToList());
}
它只是说
Delegate System.Func<System.Collections.Generic.IEnumerable<expWEBCRM.Tests.Repositories.MockObjectSet>> does not take 1 arguments
提前谢谢!
推荐答案
您需要像这样明确地指定Returns
重载的类型参数:
You need to explicitly specify the type parameters of the Returns
overload like so:
mockRepository.Setup(x => x.GetBy(It.IsAny<Expression<Func<MockObjectSet, bool>>>()))
.Returns<Expression<Func<MockObjectSet, bool>>>(predicate => mocks.Where(predicate).ToList());
编辑:存储库接受一个表达式并将其用于IQueryable
.模拟数据源实际上是一个IEnumerable
. LINQ接口的不同之处在于:一个输入一个lambda,一个输入一个表达式:
EDIT The repository takes an expression and uses it on a IQueryable
. The mock data source is actually an IEnumerable
. The difference in the LINQ interface is one takes a lambda, the one an expression:
IQueryable<T>.Where(Expression<Func<T,bool>>);
IEnumerable<T>.Where(Func<T,bool>);
在这种情况下发生的事情是尝试用Expression<Func<T,bool>>
调用IEnumerable.Where
.解决此问题的最简单方法是将源集合设置为IQueryable
:
What happens in this scenario is trying to call IEnumerable.Where
with Expression<Func<T,bool>>
. The easiest way to fix this is to have the source collection as IQueryable
:
public RepositoryTest()
{
IQueryable<MockObjectSet> mocks = new List<MockObjectSet>()
{
new MockObjectSet { FirstName = "Beta", LastName = "Alpha", Mobile = 12345678 },
new MockObjectSet { FirstName = "Alpha", LastName = "Beta", Mobile = 87654321 }
}.AsQueryable();
var mockRepository = new Mock<IRepository<MockObjectSet>>();
mockRepository.Setup(x => x.GetBy(It.IsAny<Expression<Func<MockObjectSet, bool>>>()))
.Returns<Expression<Func<MockObjectSet, bool>>>(predicate => mocks.Where(predicate).ToList());
}
这篇关于Moq-模拟通用存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!