Ric*_*ich 4 c# entity-framework entity-framework-4
我正在尝试加载SingleOrDefault实体的相关实体,但是我收到以下异常:
IEnumerable类型的导航属性不是ICollection类型的单个实现
我尝试过这几种方法,并最终针对上下文针对每个查询获得相同的错误(我在评论中包含了其他方式).
using(var context = CustomObjectContextCreator.Create())
{
return context.Job.Include("Surveys").Include("SiteInfoes")
.Where(r => r.Jobid == jobId).SingleOrDefault();
//context.ContextOptions.LazyLoadingEnabled = false;
//var Job = context.Job.Where(r => r.Jobid == jobId).SingleOrDefault();
//context.LoadProperty(Job, "Surveys");
//context.LoadProperty(Job, "SiteInfoes");
//var Job = (from j in context.Job
// .Include("Surveys")
// .Include("SiteInfoes")
// select j).SingleOrDefault();
//var Job = context.Job.Where(r => r.Jobid == jobId).SingleOrDefault();
//var surveys = context.Surveys.Where(s => s.JobID == jobId);
//var wellInfoes = context.SiteInfoes.Where(w => w.Jobid == jobId);
//Job.Surveys = surveys.ToList();
//Job.SiteInfoes = wellInfoes.ToList();
//return Job;
}
Run Code Online (Sandbox Code Playgroud)
这是我正在使用的POCO对象:
public class Job
{
public int? Jobid { get; set; }
public string JobLocation { get; set; }
public string JobName { get; set; }
public virtual IEnumerable<Survey> Surveys { get; set; }
public virtual IEnumerable<SiteInfo> SiteInfoes { get; set; }
}
public class Survey
{
public int SurveyID { get; set; }
public int? JobID { get; set; }
public DateTime? DateTime { get; set; }
public string Report { get; set; }
public virtual Job Job { get; set; }
}
public class SiteInfo
{
public int Jobid { get; set; }
public string SiteLocation { get; set; }
public virtual JobInfo JobInfo { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
如何正确加载相关实体?
IEnumerable<T>
不支持导航集合的类型.您必须使用ICollection<T>
或从它(例如衍生另一个接口IList<T>
)或具体实现的ICollection<T>
-样List<T>
,HashSet<T>
等等.