我有一些代码从我的数据库中选择一些值。我有一个IQueryable请求,其中包含ICollection of rooms。
我想要List<ICollection<rooms>>
。我尝试了以下内容,我收到了上述错误。
任何想法??
public ActionResult _roomChecker(checkRooms JSONdata){
var rooms = db.rooms.Include(r=>r.building).Include(r=>r.facilities);
rooms = rooms.Where(r => r.capacity >= JSONdata.capacity);
if (JSONdata.type != "Any")
{
rooms = rooms.Where(r => r.roomType.Equals(JSONdata.type));
}
if (JSONdata.park != "Any")
{
rooms = rooms.Where(r => r.building.park.Equals(JSONdata.park));
}
if (JSONdata.facilities != null)
{
for (var i = 0; i < JSONdata.facilities.Length; i++)
{
rooms = rooms.Where(r => r.facilities.Any(f => f.facilityName.Equals(JSONdata.facilities[i])));
}
}
var proposedRequest = db.requests.Include(r => r.rooms);
proposedRequest = proposedRequest.Where(r=>r.booked.Equals(1));
proposedRequest = proposedRequest.Where(r => r.roundID.Equals(JSONdata.roundID));
proposedRequest = proposedRequest.Where(r => r.day.Equals(JSONdata.day));
proposedRequest = proposedRequest.Where(s => s.start < JSONdata.start + JSONdata.length && s.start + s.length > JSONdata.start);
int[] standardWeeks = new int[12] {1,2,3,4,5,6,7,8,9,10,11,12};
var containsStandard = standardWeeks.Intersect(JSONdata.weeks);
if (containsStandard.Count()!=0)
{
proposedRequest = proposedRequest.Where(r => r.weeks_request.Any(f => JSONdata.weeks.Contains(f.week)) || r.weeks.Equals(1));
}
else {
proposedRequest = proposedRequest.Where(r => r.weeks_request.Any(f => JSONdata.weeks.Contains(f.week)));
}
//ERROR OCCURS ON THIS LINE BELOW
List<ICollection<room>> bookedRooms = proposedRequest.Select(r => r.rooms).ToList();
var deptRooms = db.rooms.Include(r => r.building).Include(r => r.facilities).Where(r => r.belongsTo.Equals(JSONdata.deptCode));
roomCheckerObject suitableRooms = new roomCheckerObject();
suitableRooms.code = JSONdata.deptCode;
suitableRooms.roomNo = JSONdata.roomNo;
suitableRooms.RequestNo = JSONdata.RequestNo;
if(rooms.Count() >0){
suitableRooms.rooms = rooms.ToList();
var buildings = rooms.Select(r => r.building).Distinct();
suitableRooms.buildings = buildings.ToList();
}
if(bookedRooms.Count() >0){
suitableRooms.bookedRooms = bookedRooms;
}
if(deptRooms.Count() >0){
suitableRooms.deptRooms = deptRooms.ToList();
}
return PartialView(suitableRooms);}
答案 0 :(得分:2)
很难说究竟是什么导致错误,但我可以看到3个可能的罪魁祸首:
1)您正在使用.Equals()
与Linq to entities(L2E)查询。这可能会导致问题,请参阅here。
2)您说错误发生在声明List<ICollection<room>>
的行上。在这一行中,您在任何L2E语句中首次调用.ToList()
。只有现在才能对数据库执行L2E查询(see EF Query Execution),这意味着先前的L2E语句中的任何错误(使用.Equals()
)都可能抛出异常。
3)proposedRequest.Select(r => r.rooms).ToList();
真的会返回List<ICollection<room>>
吗?尝试使用.SelectMany()
(虽然这可能会产生不良影响),或者通过完整性检查将List<ICollection<room>>
更改为var
,以查看查询将返回的内容。