I am making an MCV open-hours admin, in which I have a class Schedule containing an ICollection of ExceptionHoursSets, each HoursSet further containing a WeekSpec. (The ExceptionHoursSets contain hours which define exceptions to a general WeekSpec hours pattern also contained in Schedule.)
Schedule.cs (abbreviated):
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace HoursAdmin.Models
{
public class Schedule
{
[Required]
public Guid ScheduleId { get; set; }
// Miscellaneous props
// General hours pattern
public Guid WeekSpecId { get; set; }
public virtual WeekSpec WeekSpec { get; set; }
// All exceptions to that pattern
virtual public ICollection<ExceptionHoursSet> ExceptionHoursSets { get; set; }
}
}
ExceptionHoursSet.cs (also abbreviated):
using System;
using System.ComponentModel.DataAnnotations;
namespace HoursAdmin.Models
{
public class ExceptionHoursSet
{
[Required]
public Guid ExceptionHoursSetId { get; set; }
// More misc props
public Guid WeekSpecId { get; set; }
[Required]
public WeekSpec WeekSpec { get; set; }
}
}
WeekSpec.cs (abbreviated still):
using System;
using System.ComponentModel.DataAnnotations;
namespace HoursAdmin.Models
{
public class DaySpec
{
[Required]
public Guid DaySpecId { get; set; }
// Good old misc props
}
}
If I retrieve the Schedule, the HoursSet collection loads, but each HoursSet’s WeekSpec is null. I am currently disposed to ignore the nagging sense that I should use only Code First loading, and manually query for the WeekSpec whose ID matches that stored as the ExceptionHoursSet’s foreign key:
public ViewResult Index()
{
using (var db = new HoursDb())
{
var schedules = db.Schedules.ToList();
foreach (var schedule in schedules)
{
var exceptionHoursSets = schedule.ExceptionHoursSets;
foreach (var exceptionHoursSet in exceptionHoursSets)
{
var weekSpec = db.WeekSpecs.FirstOrDefault(d => d.WeekSpecId ==
exceptionHoursSet.WeekSpecId);
exceptionHoursSet.WeekSpec = weekSpec;
db.Entry(weekSpec).Collection(w => w.DaySpecs).Load();
}
}
return View(schedules);
}
}
However, this is repetitive and tedious… so would anyone mind furnishing how this should be done?
P.S. — The answer supplied in Auto-retrieve ICollection of complex type with Code First won’t work, because as you can see I cannot put a nav prop in the WeekSpec to its parent entity, since that entity may either be a Schedule or an ExceptionHoursSet (see How to define an MVC database structure using the same sub-table in different super-tables).
Much appreciated,
Nathan Bond
1 Answer