gpt4 book ai didi

entity-framework - 带投影的 EF4 Include()

转载 作者:行者123 更新时间:2023-12-01 13:03:14 25 4
gpt4 key购买 nike

我正在尝试做一个简单的查询,它涉及预加载和投影,但遇到了问题。我正在使用 CodeFirst CTP5,但我相信这个问题也会影响直接 EF4。

这是我的初始查询:

public List<ArticleSummary> GetArticles()
{
var articlesQuery = _db.Articles.Include(article => article.Category).Select(article => new ArticleSummary
{
Article = article,
CommentsCount = article.Comments.Count
});

return articlesQuery.ToList();
}

这导致文章的类别属性为空。如果我取出投影,它就可以正常工作。看完this ,好像提示我需要在投影之后做include,所以我把query改成了:

    public List<ArticleSummary> GetArticles()
{
var articlesQuery = _db.Articles.Select(article => new ArticleSummary
{
Article = article,
CommentsCount = article.Comments.Count
});

articlesQuery = articlesQuery.Include(x => x.Article.Category);

return articlesQuery.ToList();
}

这会导致类似于 this SO post 的异常(见下文) .

"Unable to cast the type 'System.Linq.IQueryable1' to type
'System.Data.Objects.ObjectQuery
1'. LINQ to Entities only supports casting Entity Data Model primitive types."

那么,我该怎么做呢?

最佳答案

你可以试试:

public List<ArticleSummary> GetArticles()
{
var articlesQuery = _db.Articles.Select(article => new
{
Article = article,
Category = article.Category
CommentsCount = article.Comments.Count
}
).ToList().
Select(
x => new ArticleSummary()
{
Article = x.Article,
CommentsCount = x.CommentsCount
}
);

return articlesQuery.ToList();
}

关于entity-framework - 带投影的 EF4 Include(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4580391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com