There are quite a few problems in your request:
You cannot design an object ( select new ProspectProfile ). LINQ to Entities only supports predictions in anonymous types ( select new ) or other types that are not part of your entity data model ( select new MySpecialType )
ToString() for a numeric or DateTime type is not supported in LINQ to Entities ( ServiceETA.ToString() )
FirstOrDefault().ServiceETA (or FollowUpdate ) throws an exception if the Opportunities collection is empty and ServiceETA is a non-nullable value type (such as DateTime ) because EF cannot materialize the value into such a variable.
Using .ToList() after your first query executes the query in the database and loads the full result. Your later Take occurs in memory in the full list, and not in the database. (You effectively load the entire list of results from the database into memory and then discard all objects except the first, you have Take en.
To fix all four problems, you can try the following:
var profilelst = dbContext.ProspectProfiles .Where(p => p.CreateId == currentUser) .Select(p => new { ProspectId = p.ProspectId, Live = p.Live, Name = p.Name, LastOpportunity = p.Opportunities .OrderByDescending(o => o.FollowUpDate) .Select(o => new { ServiceETA = o.ServiceETA, FollowUpDate = o.FollowUpDate }) .FirstOrDefault() }) .OrderByDescending(x => x.LastOpportunity.FollowUpDate) .Skip(startIndex)
This will give you a list of anonymous objects. If you need a result in the list of your ProspectProfile object, you must copy the values ββafter this query. Note that LastOpportunity may be null as a result if a ProspectProfile does not have Opportunities .
source share