问题
I am working on an asp.net mvc 3 web application , and i have the folloiwng model class inside my .tt folder:-
public partial class Patient
{
public Patient()
{
this.Visits = new HashSet<Visit>();
}
public int PatientID { get; set; }
//code goes here...
public virtual Gender Gender { get; set; }
**public virtual ICollection<Visit> Visits { get; set; }**
Then on the Controller class i wrote the following :-
public PartialViewResult ShowOther(int id, int skip, int take )
{
ViewBag.take = take;
Patient patient = repository.GetPatient(id);
**Visit visit = patient.Visits.OrderByDescending(d => d.Date).Skip(skip).Take(take).SingleOrDefault();**
//code goes here
So my question if wether the following Orderby patient.Visits.OrderByDescending(d => d.Date).Skip(skip).Take(take).SingleOrDefault(); be performed on the application level (which means that all the visits object will be retrived from the database and then the orderby will be done on the application level) OR the Orderby will be performed on the database and only the intended Visit object will be passed to the application?
My repository.GetPatient(id); method looks as follow:-
public Patient GetPatient(int id)
{
return entities.Patients.FirstOrDefault(d => d.PatientID == id); }
BR
回答1:
Once you access patient.Visits lazy loading will load ALL visits to you application. Everything will be done in your application.
If you want to load only single visit you try this:
entities.ContextOptions.LazyLoadingEnabled = false;
var patient = entities.Patients.FirstOrDefault(d => d.PatientID == id);
var visit = ((EntityCollection<Visit>)patient.Visists).CreateSourceQuery()
.OrderByDescending(d => d.Date)
.SingleOrDefault();
.
回答2:
Before calling .ToList(), .Single() - database level. After calling .ToList(), .Single() - application level.
In your specific example it doesn't matter as the call to FirstOrDefault in the repository method executes the query and returns the result.
来源:https://stackoverflow.com/questions/10901553/will-the-orberby-for-an-icollection-be-performed-on-the-database-level-or-appl