我正在制作一个MCV开放时间管理员,其中包含一个包含ExceptionHoursSet集合的ICollection类,每个HoursSet进一步包含一个WeekSpec。 (该ExceptionHoursSets包含用于定义例外一般WeekSpec小时图案也包含在附表小时。)EF代码优先加载不完成ICollection属性
Schedule.cs(缩写):
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(也缩写):
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(简称尚):
using System;
using System.ComponentModel.DataAnnotations;
namespace HoursAdmin.Models
{
public class DaySpec
{
[Required]
public Guid DaySpecId { get; set; }
// Good old misc props
}
}
如果我检索Schedule,HoursSet集合加载,但每个HoursSet的WeekSpec都为null。我目前配置忽略,我应该只使用代码第一次加载和手动查询其ID匹配存储为ExceptionHoursSet的外键的WeekSpec唠叨的感觉:
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);
}
}
然而,这是重复和乏味。 ..所以任何人都会介意如何做到这一点?
P.S. - 在Auto-retrieve ICollection of complex type with Code First中提供的答案将不起作用,因为您可以看到我无法将WeekSpec中的导航道具放置到其父实体,因为该实体可能是Schedule或ExceptionHoursSet(请参阅How to define an MVC database structure using the same sub-table in different super-tables)。
大加赞赏,
弥敦道债券
感谢,认为做到了。我以前尝试过某种热切的加载方式,但它不起作用。起初,你们也没有工作;然后我发现我没有使用System.Data.Entity,所以我没有得到Include扩展。 – NargothBond 2012-08-02 14:11:47