【问题标题】:Selecting specific properties from Model从模型中选择特定属性
【发布时间】:2017-03-17 16:31:21
【问题描述】:

我有以下型号:

   public class HelpApplication  {  
    public int Id { get; set; }
    public string ApplicatonName { get; set; }     
    public int DisplayOrder { get; set; }  
    public bool Available { get; set; }
    public ICollection<HelpArea> HelpAreas { get; } = new List<HelpArea>();
}

public class HelpArea {
    public int Id { get; set; }
    public string AreaName { get; set; }
    public int DisplayOrder { get; set; }
    public bool Available { get; set; }
    public int ApplicationId { get; set; }
    public virtual HelpApplication HelpApplication { get; set; }
    public ICollection<HelpTopic> HelpTopics { get; } = new List<HelpTopic>();
}

public class HelpTopic  {
    public int Id { get; set; }
    public string Title { get; set; }
    public int DisplayOrder { get; set; }
    public string Content { get; set; }
    public bool Available { get; set; }

    public int AreaId { get; set; }
    public virtual HelpArea HelpArea { get; set; }

    public ICollection<HelpArticle> HelpArticles { get; } = new List<HelpArticle>();
}

 public class HelpArticle {
    public int Id { get; set; }
    public string Title { get; set; }
    public int DisplayOrder { get; set; }
    public string Content { get; set; }
    public string Keywords { get; set; }
    public bool Available { get; set; }
    public int HelpfulYes { get; set; }
    public int HelpfulNo { get; set; }
    public int TopicId { get; set; }
}

我想使用类似下面的查询,使用HelpArticles,我只需要 3 个属性。我不需要一直拉Content(A CLOB),除非需要。

this.Entities
            .Include(h => h.HelpTopics)
            .ThenInclude(s => s.HelpArticles.Select(t => new { t.Title, t.Keywords, t.DisplayOrder} ))
            .Where(h => h.ApplicationId == appId).ToList();

以上查询返回异常:

属性表达式's => {from HelpArticle t in s.HelpArticles select new f__AnonymousType12`3(Title = [t].Title, Keywords = [t].Keywords, DisplayOrder = [t].DisplayOrder) }' 无效。 该表达式应表示属性访问:'t => t.MyProperty'。

我想返回以下内容:

HelpApplication中的所有属性;

帮助主题集合 标题, 显示顺序, 可用,

帮助文章集 标题, 显示顺序, 可用的, 关键词

【问题讨论】:

  • 整个查询执行的结果你想返回什么?
  • 问题已更新。
  • 你不能那样做。您需要为 HelpApplication 及其子项类型创建一个代理,然后仅将您要检索的数据投射到这些代理。

标签: c# asp.net entity-framework asp.net-core-mvc entity-framework-core


【解决方案1】:

我认为您不能在 Include 方法中使用匿名类型。您可以引用要预加载的导航属性,但不能将属性投影到匿名类型中。如果问题是Content 负载过重,并且大多数时候您不需要它,您可以将表格映射到两个不同的实体HelpArticleContent 并导航HelpArticle.Content 以获取@987654326 @(在 EF 6.1 中延迟加载)当你需要它时。 EF 有一个称为表拆分的功能,顾名思义,这允许将一个数据库表映射(拆分)到概念模型中的多个类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 2016-07-26
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    相关资源
    最近更新 更多