In controller I have a query and its result will be displayed in the View.
This is how the query result model looks like:
public class Timesheet
{
[Key]
public virtual int TimesheetId { get; set; }
[Required]
public virtual int TimesheetWeek { get; set; }
[Required]
public virtual DateTime TimesheetWeekStarts { get; set; }
[Required]
public virtual DateTime TimesheetWeekEnds { get; set; }
[Required]
public virtual string TimesheetOwner { get; set; }
[Required]
public virtual ICollection<TimesheetEntry> TimesheetEntries { get; set; }
}
And here is the TimesheetEntry model:
public class TimesheetEntry
{
[Key]
public virtual int EntryId { get; set; }
[Required]
public virtual DateTime EntryDate { get; set; }
[Required]
public virtual double TotalHours { get; set; }
public Timesheet Timesheet { get; set; }
[Display(Name = "Project number")]
[ForeignKey("Project")]
public virtual int ProjectId { get; set; }
public virtual Project Project { get; set; }
}
The query will always return only one Timesheet class, with multiple TimesheetEntries. Usually I would expect the number of entries to be certain number. Lets say in this case it should be 56. So if the
TimesheetEntries.Count() != 56
I will add additional entries manually to the query result to ensure that the number of entries is as required. Once done, I will order entries by Date.
TimesheetEntries.OrderBy(x => x.EntryDate).OrderBy(x => x.Project);
Some Pseudo code to show the process which got me to my problem:
public void PseudoCode()
{
const int REQUIRED_NUMBER_OF_ENTRIES = 45;
//this will return only one instance of model due to .FirstOrDefault()
var result = this.db.Timesheets.Where(x => x.TimesheetWeekStarts <= DateTime.Now).Select(x => x)
.Where(x => x.TimesheetOwner == User.Identity.Name)
.FirstOrDefault();
if (result != null)
{
//if number of entries is not what I expect
if(result.TimesheetEntries.Count() < REQUIRED_NUMBER_OF_ENTRIES)
{
//check how many to add
int entriesMissing = REQUIRED_NUMBER_OF_ENTRIES - result.TimesheetEntries.Count();
//add missing entries as empty entries
for (int i = 0; i < entriesMissing; i++)
{
result.TimesheetEntries.Add(
new TimesheetEntry
{
//to shorten this I am only adding DateTime.Now, normaly different times/dates would be added
EntryDate = DateTime.Now,
TotalHours = 8
});
}
}
}
result.TimesheetEntries.OrderBy(x => x.EntryDate).OrderBy(x => x.ProjectId);
}
Here is the result of sorting:
so the the list contains ordered DynamicProxies first and then ordered manually added entries.
But the order should have been:
- DynamicProxies.TimesheetEntry
- TimesheetEntry
- TimesheetEntry
- DynamicProxies.TimesheetEntry ... etc
Why is this? Why the order result is ordered this way? Or am I doing this completely wrong ...