C# 在select语句中从IEnumerable强制转换为Queryable?
我有一个数据库存储库,其中包含一系列访问功能。我现在想构建一个假的存储库,它为unittests提供类似的功能。与真实的存储库不同,此存储库使用简单的列表,而不是linqtosql生成的模型类 大多数伪造的存储库函数看起来与真实的存储库函数完全相同,只是在最后有一个额外的ToQueryable()。然而,我现在有一个似乎需要更复杂的演员阵容C# 在select语句中从IEnumerable强制转换为Queryable?,c#,unit-testing,model-view-controller,C#,Unit Testing,Model View Controller,我有一个数据库存储库,其中包含一系列访问功能。我现在想构建一个假的存储库,它为unittests提供类似的功能。与真实的存储库不同,此存储库使用简单的列表,而不是linqtosql生成的模型类 大多数伪造的存储库函数看起来与真实的存储库函数完全相同,只是在最后有一个额外的ToQueryable()。然而,我现在有一个似乎需要更复杂的演员阵容 public class FakeUserRepository : IUserRepository { public IQuery
public class FakeUserRepository : IUserRepository {
public IQueryable<SelectListItem> GetRecords(int userid) {
// fake_table is a list
return (from a in fake_table select
new SelectListItem {
Value = a.ID.ToString(),
Text = a.Name
});
}
}
公共类FakeUserRepository:IUserRepository{
公共IQueryable GetRecords(int userid){
//表是一个列表
返回(从表中选择)
新建SelectListItem{
Value=a.ID.ToString(),
Text=a.名称
});
}
}
目前,这会导致错误“无法隐式转换类型”System.Collections.Generic.IEnumerable。)我对错误消息并不感到惊讶,但我不知道如何修复强制转换。IEnumerable上有一个.AsQueryable()扩展方法仅用于此,因此请将其添加到返回的查询中
return (from ..).AsQueryable();
你可以做:
public class FakeUserRepository : IUserRepository {
public IQueryable<SelectListItem> GetRecords(int userid) {
// fake_table is a list
return (from a in fake_table select
new SelectListItem {
Value = a.ID.ToString(),
Text = a.Name
}).AsQueryable<SelectListItem>;
}
}
公共类FakeUserRepository:IUserRepository{
公共IQueryable GetRecords(int userid){
//表是一个列表
返回(从表中选择)
新建SelectListItem{
Value=a.ID.ToString(),
Text=a.名称
}).AsQueryable;
}
}
只需在linq查询的末尾添加.AsQueryable(),就可以了