简体   繁体   English

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

[英]How do I load related entities of type IEnumerable<T>

I'm trying to load related entities of a SingleOrDefault entity, but I am getting the following exception: 我正在尝试加载SingleOrDefault实体的相关实体,但是我收到以下异常:

The navigation property of type IEnumerable is not a single implementation of type ICollection IEnumerable类型的导航属性不是ICollection类型的单个实现

I've tried doing this several ways and ultimately get the same error above for each query against the context (I've included the other ways in comments). 我尝试过这几种方法,并最终针对上下文针对每个查询获得相同的错误(我在评论中包含了其他方式)。

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;
        }

Here are the POCO objects I'm using: 这是我正在使用的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; }
    }

How do I properly load the related entities? 如何正确加载相关实体?

IEnumerable<T> is not supported as a type for a navigation collection. IEnumerable<T>不支持作为导航集合的类型。 You must use ICollection<T> or another interface derived from it (for example IList<T> ) or a concrete implementation of ICollection<T> - like List<T> , HashSet<T> , etc. 您必须使用ICollection<T>或从其派生的其他接口(例如IList<T> )或ICollection<T>的具体实现 - 如List<T>HashSet<T>等。

那是因为你需要ICollection而不是IEnumerable。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM