我有一个存储过程,它返回映射到同名DBML对象的表(InstitutionEntityIP)中的所有列。它将返回n个记录。但是,代码隐藏默认为ISingleResult。 我想让它返回一个IEnumerable。
我收到错误消息'查询结果不能多次枚举。'
我的代码如下所示:
//ContentRepository.cs
private readonly IGIGlobalDataContext db;
// ....
public IEnumerable<InstitutionEntityIP> GetInstitutionEntityIPs(long fromIp, long toIp)
{
return
from ip in db.InstitutionEntityIPs
where
(
(fromIp >= ip.FromIPInteger && fromIp <= ip.ToIPInteger) || //From IP Address parameter is the same or encompassed
(toIp >= ip.FromIPInteger && toIp <= ip.ToIPInteger) || //To IP Address parameter is the same or encompassed
(fromIp <= ip.FromIPInteger && toIp >= ip.FromIPInteger) || //Any From IPs in the DB between the parameters
(fromIp <= ip.ToIPInteger && toIp >= ip.ToIPInteger) //Any To IPs in the DB between the parameters
) &&
ip.IsActive &&
ip.InstitutionEntity.IsActive &&
Convert.ToDateTime((ip.InstitutionEntity.ExpirationDate ?? (DateTime?)DateTime.Now)) >= DateTime.Now &&
ip.InstitutionEntity.Institution.IsActive &&
Convert.ToDateTime((ip.InstitutionEntity.Institution.ExpirationDate ?? (DateTime?)DateTime.Now)) >= DateTime.Now
select ip;
}
public IEnumerable<InstitutionEntityIP> GetInstitutionEntityIPs(string fromIp, string toIp)
{
// SearchForConflictingIPs is the method name created when I drop my
// stored procedure (also called SearchForConflictingIPs) on the DBML layout
var ips = db.SearchForConflictingIPs(fromIp, toIp); // returns ISingleResult<InstitutionEntityIP>
// VVVVVVVVV
return ips.ToList(); // <-- Needed to specify the .ToList() here <--
// ^^^^^^^^^
}
// I actually call the method from another class
public static IEnumerable<IGIGlobal_DAL.InstitutionEntityIP> ConflictingIPs(string start, string end)
{
var cr = new ContentRepository();
return cr.GetInstitutionEntityIPs(start, end);
}
public RangeValidationResult Validate(bool isUpdate = false, int institutionEntityIPID = 0)
{
var conflicts = ConflictingIPs(Start.ToString(), End.ToString());
if (conflicts.Any()) // <---- 'The query results cannot be enumerated more than once.'
{
var conflictingEntities = string.Join(", ", conflicts.Select(c => c.InstitutionEntity.InstitutionEntity1).Distinct());
}
}
如果您需要我提供更多信息,请发表评论。
答案 0 :(得分:1)
我需要在公共IEnumerable GetInstitutionEntityIPs(字符串fromIp,string toIp)方法中指定.ToList()。
找到我需要的信息:
The result of a query cannot be enumerated more than once
答案 1 :(得分:0)
DBML文件中的存储过程生成的函数将返回ISingleResult
,其行为类似于DataReader
。您只能让枚举器只循环一次。
在你的情况下:
if (conflicts.Any()) // <---- 'The query results cannot be enumerated more than once.'
表示枚举器已被使用。此处Any()
还尝试让枚举器执行检查是否存在至少1条记录。
因此,如果您需要在集合上多次循环,则需要使用该枚举器将每个ISingleResult
转换为列表。因此,在这种情况下你必须忍受ToList()
。