如何加载IEnumerable类型的相关实体?

本文关键字:类型 实体 何加载 加载 IEnumerable | 更新日期: 2023-09-27 18:12:58

我试图加载一个SingleOrDefault实体的相关实体,但我得到以下例外:

IEnumerable类型的navigation属性不是iccollection类型的单个实现

我已经尝试了几种方法,最终对上下文的每个查询都得到了上面相同的错误(我在注释中包含了其他方法)。

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;
        }
以下是我使用的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; }
    }

如何正确加载相关实体?

如何加载IEnumerable<T>类型的相关实体?

IEnumerable<T>不支持作为导航集合的类型。您必须使用ICollection<T>或从它派生的其他接口(例如IList<T>)或ICollection<T>的具体实现-如List<T>, HashSet<T>

这是因为你需要的是ICollection而不是IEnumerable