Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# LINQ to实体中不支持指定的类型成员_C#_Linq_Entity Framework - Fatal编程技术网

C# LINQ to实体中不支持指定的类型成员

C# LINQ to实体中不支持指定的类型成员,c#,linq,entity-framework,C#,Linq,Entity Framework,我有一组故事和注释,我试图在被API调用时返回一个较小的DTO实体 我正试图仅检索最后一条注释,但得到的错误是“LINQ to Entities中不支持指定的类型成员'LastComment'。只支持初始值设定项、实体成员和实体导航属性。” 我的故事: public Story() { Comments = new List<Comment>(); } public int StoryId { get; set; } public List<Comment> Co

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

我正试图仅检索最后一条注释,但得到的错误是“LINQ to Entities中不支持指定的类型成员'LastComment'。只支持初始值设定项、实体成员和实体导航属性。”

我的故事:

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

public Comment LastComment
{
    get
    {
        return Comments.LastOrDefault();
    }
}
公共故事()
{
注释=新列表();
}
public int StoryId{get;set;}
公共列表注释{get;set;}
公众评论最后评论
{
得到
{
返回注释。LastOrDefault();
}
}
还有我的API获取方法:

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

           };
}
public IEnumerable Get()
{
从p返回db.Stories
.Include(x=>x.Comments)
选择new StoryDTO()
{
StoryId=p.StoryId,
LastComment=p.LastComment,
NumberOfComments=p.Comments.Count
};
}

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

您可以尝试以下代码:

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

           };

通过这种方式,您将处理LINQ to对象,EF不会尝试将所有内容转换为SQL

如果我想添加一个额外的谓词,则其他示例的可能副本是可以的,但这里我尝试获取列表的最后一项,我不确定从何处开始其他示例仍然适用。将
p.LastComment
更改为
p.Comments.LastOrDefault()
应该会起作用。更改为p.Comments.LastOrDefault()不起作用我建议最好调用
AsEnumerable()
而不是
ToList()
,这样可以避免创建不必要的
列表。@BenRobinson yep,效果将是一样的