【问题标题】:Entity Framework: InvalidOperationException when including mutiple levels of properties实体框架:包含多级属性时出现 InvalidOperationException
【发布时间】:2016-07-28 00:50:07
【问题描述】:

我正在使用实体框架核心。我正在尝试创建产品列表并包含相关评论和评论作者数据。

我有 3 个实体:

public class Product
{
    [Key]
    public int ID { get; set; }
    public ICollection<Review> Reviews {get; set;}
}

public class Review
{
        [Key]
        public int ID { get; set; }
        public Product Product {get; set;}
        public Customer Author { get; set; }
}

public class Customer
{
        [Key]
        public int ID { get; set; }
        public ICollection<Review> Reviews { get; set; }
}

当我引用 this answer 时,我要求提供带有评论和作者的产品列表:

context.Products.Include(p=> p.Reviews.Select(r => r.Author)).ToList();

抛出以下错误:

System.InvalidOperationException
消息 = 属性表达式 'p => {from Review r in [p].Reviews select [r].Author}' 无效。该表达式应表示属性访问:'t => t.MyProperty'

任何建议将不胜感激。

【问题讨论】:

  • 你有流畅的映射吗?
  • 我没有流畅的映射。

标签: entity-framework-core


【解决方案1】:

这似乎是一些尚未完成或缺少的东西,但无论如何你都可以这样做:

context.Products.Include(p => p.Reviews).ThenInclude(x=>x.Author).ToList();

【讨论】:

  • 谢谢@Bassam :) 但是,在您的示例中,“x”的类型是 ICollection,而不是 Review。所以我认为这行不通。
  • @StevePaul 这与您的查询完全一样,并且正在运行!试试吧^^
  • 我的道歉 - 你是对的,我错了!出于某种原因,它引发了编译错误。我重新编译了我的模型类,错误消失了!我很困惑。但是谢谢你的时间:)
猜你喜欢
  • 1970-01-01
  • 2013-09-06
  • 1970-01-01
  • 2012-06-05
  • 1970-01-01
  • 2011-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多