I'm having an issue with combining multiple ef6 linq queries
Here the code works when the two linq queries are separated
List<int> skipRoomIds = hbContext.Reservations.Include(x => x.Room)
.Where(x => (x.FromDate < fromDate && fromDate < x.ToDate) || (x.FromDate < toDate && toDate < x.ToDate) ||
(fromDate < x.FromDate && x.FromDate < toDate) || (fromDate < x.ToDate && x.ToDate < toDate))
.Select(x => x.Room.Id).ToList(); //First query
roomRows = hbContext.Rooms.Where(x => !skipRoomIds.Contains(x.Id) && x.MaxNumOfPeople >= numOfPeople)
.Select(x=> new RoomRow() { From = fromDate, To = toDate, Room = x}).ToList(); //Second query
But when I try and combine the two I get an error:
System.NotSupportedException: 'LINQ to Entities does not recognize the method 'System.Linq.IQueryable`1[HotelBooker.Models.Reservation] Include[Reservation,Room](System.Linq.IQueryable`1[HotelBooker.Models.Reservation], System.Linq.Expressions.Expression`1[System.Func`2[HotelBooker.Models.Reservation,HotelBooker.Models.Room]])' method, and this method cannot be translated into a store expression.'
In the first linq query I get a list of integers to then use to check something in the where part of the second linq query, but then when I put the first linq query inside the second one it doesn't work.
Why would I want that ? well so I don't send more requests to the sql server then necessary.
roomRows = hbContext.Rooms.Where(z => !hbContext.Reservations.Include(x => x.Room)
.Where(x => (x.FromDate < fromDate && fromDate < x.ToDate) || (x.FromDate < toDate && toDate < x.ToDate) ||
(fromDate < x.FromDate && x.FromDate < toDate) || (fromDate < x.ToDate && x.ToDate < toDate))
.Select(x => x.Room.Id).AsEnumerable().Contains(z.Id)
&& z.MaxNumOfPeople >= numOfPeople)
.Select(z => new RoomRow() { From = fromDate, To = toDate, Room = z }).ToList();
Can anybody explain why combining multiple linq queries doesn't work with ef6 or if I'm doing it wrong ? and how would you do select statements in where or select part of an sql statement in linq ef6 ?
Sql statement example:
select * from table where id in (select id in table2);
I have tried searching for the answer but couldn't find anything, perhaps I had the wrong keywords when searching the problem.
Related
I want to use '!' to exclude the following records in my .Where.
What is the syntax?
// where do I put the ! to get the syntax correct
.Where(p => p.StartDate >= startDate && p.EndDate <= DateTime.Now.Date)
.Where(p => !(p.StartDate >= startDate && p.EndDate <= DateTime.Now.Date))
OR
.Where(p => p.StartDate < startDate || p.EndDate > DateTime.Now.Date)
how to write a linq query with to get records between 9 am 5 pm only. the records beyond that should be discarded.
timestamp datatype
code
var items = Pirs.Where(a => !a.dataFrame.EndsWith("AAAAAAAAAAA=") && (fromDate == null || fromDate.Value.Date <= TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(a.timestamp), TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")).Date) && (toDate == null || toDate.Value.Date >= TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(a.timestamp), TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")).Date))
.GroupBy(a => a.dataFrame.Substring(a.dataFrame.Length - 12))
.Select(g => g.First()).OrderBy(a => a.timestamp);
Pirs.Where(a.timestamp.TimeOfDay > new TimeStamp(9, 0, 0) && //all times after 9am
a.timestamp.TimeOfDay < new TimeStamp(17, 0, 0) && //all times before 5pm
a.timestamp.Date > fromDate && //all dates after fromData
a.timestamp.Date < toDate) //all dates before toDate
Do the following in where condition
TimeSpan span = TimeSpan.Parse("09:00:00");
TimeSpan espan = TimeSpan.Parse("17:00:00");
Pirs.Where(a => a.timestamp >= startDate && a.timestamp <= toDate && a.timestamp.TimeOfDay >= span && a.timestamp.TimeOfDay <= espan);
I am doing the below linq query which is costing me a lot and this query is in a loop which I can not avoid and I have to do it in C# which also I can not avoid. I have lot of logic above the linq query and after the query. I wanted to check if I can change anything on the query to improve the performance at least a little bit.
lstDataTable.Where(i => i.Field<int>("ALLL_Snapshot_ID") == 20 &&
i.Field<int>("ALLL_Analysis_Segment_Group_Column_ID") == 5 &&
i.Field<DateTime>("OriginationDate") > startingSnapshotDate &&
i.Field<DateTime>("OriginationDate") <= endingSnapshotDate &&
snapshotDataWithDate.Select(j => j.Field<string>
("MaturityDateBorrowerIdNoteNumberKey")).Contains(i.Field<string>
("MaturityDateBorrowerIdNoteNumberKey")) &&
snapshotDataWithDate.Select(j => j.Field<string>
("OriginationDateBorrowerIdNoteNumberKey")).Contains(i.Field<string>
("OriginationDateBorrowerIdNoteNumberKey")))
.Select(i => i.Field<Decimal>("BalanceOutstanding") + i.Field<Decimal>
("UndisbursedCommitmentAvailability")).Sum();
where lstDataTable and snapshotDataWithDate are IEnumerable of DataRow.
I tried above query using join but it is not joining properly. The difference between the two results is way high. Below is the query I tried using join
(from p in lstDataTable
join t in snapshotDataWithDate on p.Field<string>
("MaturityDateBorrowerIdNoteNumberKey") equals t.Field<string>
("MaturityDateBorrowerIdNoteNumberKey") &&
p.Field<string>("OriginationDateBorrowerIdNoteNumberKey") equals
t.Field<string>("OriginationDateBorrowerIdNoteNumberKey")
where p.Field<int>("ALLL_Analysis_Segment_Group_Column_ID") ==
SegmentGroupCECLSurvivalRateObj.ALLL_Segment_Group_Column_ID &&
p.Field<DateTime>("OriginationDate") > startingSnapshotDate &&
p.Field<DateTime>("OriginationDate") <= endingSnapshotDate
select p.Field<Decimal>("BalanceOutstanding") + p.Field<Decimal>
("UndisbursedCommitmentAvailability")).Sum();
Try this query, I have changed some expressions in where clause.
lstDataTable.Where(i => i.Field<int>("ALLL_Snapshot_ID") == 20 &&
i.Field<int>("ALLL_Analysis_Segment_Group_Column_ID") == 5 &&
i.Field<DateTime>("OriginationDate") > startingSnapshotDate &&
i.Field<DateTime>("OriginationDate") <= endingSnapshotDate &&
snapshotDataWithDate.Any(j => j.Field<string>
("MaturityDateBorrowerIdNoteNumberKey") == i.Field<string>
("MaturityDateBorrowerIdNoteNumberKey")) &&
snapshotDataWithDate.Any(j => j.Field<string>
("OriginationDateBorrowerIdNoteNumberKey") == i.Field<string>
("OriginationDateBorrowerIdNoteNumberKey")))
.Select(i => i.Field<Decimal>("BalanceOutstanding") + i.Field<Decimal>
("UndisbursedCommitmentAvailability")).Sum();
Perhaps pulling out the Field accesses will provide a small amount of optimization?
var snapshotDataConvertedMDB = snapshotDataWithDate.Select(r => r.Field<string>("MaturityDateBorrowerIdNoteNumberKey")).ToList();
var snapshotDataConvertedODB = snapshotDataWithDate.Select(r => r.Field<string>("OriginationDateBorrowerIdNoteNumberKey")).ToList();
var ans = lstDataTable
.Select(r => new {
ALLL_Snapshot_ID = r.Field<int>("ALLL_Snapshot_ID"),
ALLL_Analysis_Segment_Group_Column_ID = r.Field<int>("ALLL_Analysis_Segment_Group_Column_ID"),
OriginationDate = r.Field<DateTime>("OriginationDate"),
MaturityDateBorrowerIdNoteNumberKey = r.Field<string>("MaturityDateBorrowerIdNoteNumberKey"),
OriginationDateBorrowerIdNoteNumberKey = r.Field<string>("OriginationDateBorrowerIdNoteNumberKey"),
BalanceOutstanding = r.Field<Decimal>("BalanceOutstanding"),
UndisbursedCommitmentAvailability = r.Field<Decimal>("UndisbursedCommitmentAvailability")
})
.Where(i => i.ALLL_Snapshot_ID == 20 &&
i.ALLL_Analysis_Segment_Group_Column_ID == 5 &&
i.OriginationDate > startingSnapshotDate &&
i.OriginationDate <= endingSnapshotDate &&
snapshotDataConvertedMDB.Contains(i.MaturityDateBorrowerIdNoteNumberKey) &&
snapshotDataConvertedODB.Contains(i.OriginationDateBorrowerIdNoteNumberKey))
.Select(i => i.BalanceOutstanding + i.UndisbursedCommitmentAvailability)
.Sum();
x.CreateDate DateTime is stored in our database down to milliseconds. My dateTimePicker values startdate and enddate only allows for querying down to seconds.
How can change my query to ignore the milliseconds of x.CreateDate? I thought the code I wrote below would work but it is not.
if (stardDateIsValid && endDateIsValid && startdate == enddate)
query = _context.Logs
.Where(x => x.ApplicationID == applicationId &&
x.CreateDate.AddMilliseconds(-x.CreateDate.Millisecond) == startdate)
.OrderByDescending(x => x.ID)
.Take(count);
var query = from l in _context.Logs
where l.ApplicationID == applicationId
&& SqlMethods.DateDiffSecond(l.CreateDate,startdate) == 0
orderby l.ID descending
select l).Take(count);
This avoids converting every date in you table into a string and the subsequent string comparison, by comparing the two dates as dates.
Getting CreateDate and startdate in the same format will help you compare apples to apples. This should accomplish that.
if (stardDateIsValid && endDateIsValid && startdate == enddate)
query = _context.Logs
.Where(x => x.ApplicationID == applicationId &&
x.CreateDate.ToString(#"MM/DD/YYYY h:mm:ss") == startdate.ToString(#"MM/DD/YYYY h:mm:ss")
.OrderByDescending(x => x.ID)
.Take(count);
I have no idea why I could not get any results from the queries posted above as I tried several variations of their themes. However I did get it working correctly by adding milliseconds to the startdate and enddate variables and it s working.
if (stardDateIsValid && endDateIsValid)
startdate = startdate.AddMilliseconds(000);
enddate = enddate.AddMilliseconds(999);
query = _context.Logs.Where(x => x.ApplicationID == applicationId && x.CreateDate >= startdate && x.CreateDate <= enddate).OrderByDescending(x => x.ID).Take(count);
You can create extension method.
public const long TicksPerMillisecond = 10000;
public const long TicksPerSecond = TicksPerMillisecond * 1000;
public static bool IsEqualIgnoreMilliseconds(this DateTime date, DateTime compareDate)
{
long tickDiff = date.Ticks - compareDate.Ticks;
return tickDiff > 0 ? tickDiff < TicksPerSecond : tickDiff < -TicksPerSecond;
}
Then you can use this:
if (stardDateIsValid && endDateIsValid && startdate == enddate)
query = _context.Logs
.Where(x => x.ApplicationID == applicationId &&
x.CreateDate.IsEqualIgnoreMilliseconds(startdate)
.OrderByDescending(x => x.ID)
.Take(count);
I'm trying to create a basic room availability statement to use with linq to entity framework. I have two tables: 'Room' including columns RoomID/RoomSize and 'Booking' including BookingID/RoomID/StartDate/Enddate.
I have got a working sql statement:
SELECT RoomID, RoomSize from Room
where RoomID NOT IN (SELECT RoomID from booking
where ('08/01/2015' >= [start] AND '08/01/2015' <= [end]) OR ('08/20/2015' >= [start] AND '08/20/2015' <= [end]))
I have got this far with the linq to entity statement:
var rooms = (from r in db.Rooms
where !(((from b in db.Bookings
where (startDate >= b.StartDate && endDate <= b.EndDate) || (endDate >= b.StartDate && endDate <= b.EndDate)).Contains(r.RoomID))
select new AvailableRoom
{
ID = r.RoomID,
Size = r.RoomSize
});
I get an error at the last bracket before .Contains(r.RoomID) saying I should have a select statement but I just can't seem to get it working.
Any suggestions would be welcome.
If you reckon using lambdas would be better/easier please feel free to suggest and example. I'm just not too familiar with them myself.. yet.
Thank you.
You can use LINQ !...Any() for the SQL NOT IN(), like so :
var rooms = (from r in db.Rooms
where !db.Bookings
.Where(b => (startDate >= b.StartDate && endDate <= b.EndDate)
||
(endDate >= b.StartDate && endDate <= b.EndDate)
)
.Any(b => b.RoomID == r.RoomID)
select new AvailableRoom
{
ID = r.RoomID,
Size = r.RoomSize
});