摘要:[Entity Framework] Exeption: The entity or complex type ' ' cannot be constructed in a LINQ to Entities query
在使用linq to entities 撈資料的時候, 出現了這樣的錯誤訊息:
The entity or complex type 'BlogMgmtModel.BlogArticle' cannot be constructed in a LINQ to Entities query.
出錯的程式碼如下:
BlogArticle q1 = _blogArticleRepository.Query().Where(r => r.BlogArticleID > 10)
.Select(rlt => new BlogArticle { AuditStatus = rlt.AuditStatus, BlogArticleID = rlt.BlogArticleID })
.FirstOrDefault();
上Stackoverflow查了一下, 有下面這一段說明
In Linq-to-Entities you can only project to an anonymous type or a regular class. You can't project to an existing entity type. You can with linq-to-objects like so..
因此, 我們這邊必須將程式改成
//solusion A
var blogArticle = _blogArticleRepository.Query().Where(r => r.BlogArticleID > 10)
.Select(rlt => new { AuditStatus = rlt.AuditStatus, BlogArticleID = rlt.BlogArticleID })
.FirstOrDefault();
//solusion B
BlogArticle blogArticle2 = _blogArticleRepository.Query().Where(r => r.BlogArticleID > 10)
.AsEnumerable()
.Select(rlt => new BlogArticle { AuditStatus = rlt.AuditStatus, BlogArticleID = rlt.BlogArticleID })
.FirstOrDefault();