【问题标题】:How do I load related entities of type IEnumerable<T>如何加载 IEnumerable<T> 类型的相关实体
【发布时间】:2011-10-29 16:29:00
【问题描述】:

我正在尝试加载 SingleOrDefault 实体的相关实体,但出现以下异常:

IEnumerable 类型的导航属性不是 ICollection 类型的单一实现

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

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

如何正确加载相关实体?

【问题讨论】:

    标签: c# entity-framework entity-framework-4


    【解决方案1】:

    IEnumerable&lt;T&gt; 不支持作为导航集合的类型。您必须使用ICollection&lt;T&gt; 或从它派生的另一个接口(例如IList&lt;T&gt;)或ICollection&lt;T&gt; 的具体实现 - 例如List&lt;T&gt;HashSet&lt;T&gt; 等。

    【讨论】:

    • 听起来这就是异常告诉我的。感谢您的澄清。
    • 您能解释一下为什么不支持 IEnumerable 吗? - 我非常想知道。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      • 2014-12-25
      • 2015-09-21
      相关资源
      最近更新 更多