I have a database with 2 million records and I have to sort them and output the results in JSON (WebAPI project).
Here is my code:
CODE1
var start = Convert.ToDateTime(startdatetime.Split(new[] { ':' }, 2)[0]).Date;
var end = Convert.ToDateTime(enddatetime.Split(new[] { ':' }, 2)[0]).Date;
var result = (from request in db.Requests
where ((Convert.ToDateTime(request.DateTime.Split(new[] { ':' }, 2)[0]).Date >= start)
&&
(Convert.ToDateTime(request.DateTime.Split(new[] { ':' }, 2)[0]).Date <= end))
group request.IP_or_Host by request.IP_or_Host into g
orderby (g.Count()) descending
select g.Key).Distinct().Take(n).ToList();
return result;
This code throws the error:
LINQ to Entities does not recognize the method
Earlier it was like this:
CODE2
var start = Convert.ToDateTime(startdatetime.Split(new[] { ':' }, 2)[0]).Date;
var end = Convert.ToDateTime(enddatetime.Split(new[] { ':' }, 2)[0]).Date;
var result = (from request in db.Requests.ToList()
where ((Convert.ToDateTime(request.DateTime.Split(new[] { ':' }, 2)[0]).Date >= start)
&&
(Convert.ToDateTime(request.DateTime.Split(new[] { ':' }, 2)[0]).Date <= end))
group request.IP_or_Host by request.IP_or_Host into g
orderby (g.Count()) descending
select g.Key).Distinct().Take(n).ToList();
return result;
But if the database has too many records it throws an outofmemory exception. What do I have to do to retrieve and sort data from the database in a memory efficient manner using LINQ?