【问题标题】:The specified type member is not supported in LINQ to EntitiesLINQ to Entities 不支持指定的类型成员
【发布时间】:2015-01-27 01:49:21
【问题描述】:

我有一组故事和评论,我试图在被 API 调用时返回一个较小的 DTO 实体。

我正在尝试仅检索最后一条评论,但收到错误消息“LINQ to Entities 不支持指定类型成员 'LastComment'。仅支持初始化程序、实体成员和实体导航属性。”

我的故事.cs:

public Story()
{
    Comments = new List<Comment>();
}
public int StoryId { get; set; }
public List<Comment> Comments { get; set; }

public Comment LastComment
{
    get
    {
        return Comments.LastOrDefault();
    }
}

还有我的 API GET 方法:

public IEnumerable<StoryDTO> Get()
{
    return from p in db.Stories
               .Include(x => x.Comments)
           select new StoryDTO()
           {
               StoryId = p.StoryId,
               LastComment = p.LastComment,
               NumberOfComments = p.Comments.Count

           };
}

我预计 Linq 无法将我的查询转换为 SQL,但我不确定解决此问题的正确方法。

【问题讨论】:

标签: c# linq entity-framework


【解决方案1】:

你可以试试下面的代码:

return (db.Stories.Include(x => x.Comments)).AsEnumerable().Select(p => 
           new StoryDTO()
           {
               StoryId = p.StoryId,
               LastComment = p.LastComment,
               NumberOfComments = p.Comments.Count

           };

这样您将处理 LINQ to Objects 并且 EF 不会尝试将所有内容转换为 SQL

【讨论】:

  • 我建议最好调用AsEnumerable() 而不是ToList(),这样可以避免创建不必要的List&lt;T&gt;
  • @BenRobinson 是的,效果是一样的
猜你喜欢
  • 2012-07-17
  • 2013-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-28
  • 1970-01-01
  • 2018-02-19
  • 2015-07-25
相关资源
最近更新 更多