The entity or complex type 'fujenDBModel.NEWS' cannot be constructed in a LINQ to Entities query.
在使用LINQ技術撈資料的時候卻出現了一個問題為
The entity or complex type 'fujenDBModel.NEWS' cannot be constructed in a LINQ to Entities query.
一開始不知道為什麼會變成這樣,這到底要怎麼解阿?
先來敘述一下問題原由,
我擁有一個後端配合資料庫技術的project,採用的是.NET MVC架構,
Model當然是採用ADO.NET Entity Data Model,
前端程式請參考上圖,我後端於Controller裡程式如下
namespace BrookeProgramDesign.Areas.Dentist.Controllers.AdminConsole
{
public class AdminConsoleNEWSController : Controller
{
private fujenDBEntities db = new fujenDBEntities();
// GET: Dentist/NEWS
public ActionResult Index()
{
var result = from NEWS in db.NEWS
join NEWS_DATE in db.NEWS_DATE on NEWS.news_id equals NEWS_DATE.news_id
orderby NEWS_DATE.year, NEWS_DATE.month, NEWS_DATE.day, NEWS_DATE.time descending
select new NEWS
{
news_id = NEWS.news_id,
title = NEWS.title,
date = NEWS.date,
category_id = NEWS.category_id,
context = NEWS.context
};
return View(result);
}
}
}
資料表NEWS的結構為
我的程式目地很簡單,就是間接對NEWS資料表裡的資料作排序,
然後再吐回NEWS資料內所有內容,
但後端的LINQ寫法是有問題的,這種寫法是LINQ to Object寫法,
我已知前端預定要binding的資料型態為
@model IEnumerable<BrookeProgramDesign.Areas.Dentist.Models.NEWS>
所以我才會去湊齊NEWS資料表裡所有的資料行然後再回傳該IEnumerable<NEWS>型態的變數,
但該錯誤「The entity or complex type 'fujenDBModel.NEWS' cannot be constructed in a LINQ to Entities query.」
指出只接受LINQ to Entity寫法,所以應改成如下
namespace BrookeProgramDesign.Areas.Dentist.Controllers.AdminConsole
{
public class AdminConsoleNEWSController : Controller
{
private fujenDBEntities db = new fujenDBEntities();
// GET: Dentist/NEWS
public ActionResult Index()
{
var result = from NEWS in db.NEWS
join NEWS_DATE in db.NEWS_DATE on NEWS.news_id equals NEWS_DATE.news_id
orderby NEWS_DATE.year, NEWS_DATE.month, NEWS_DATE.day, NEWS_DATE.time descending
select NEWS;
return View(result);
}
}
}
變成不需要自行再湊齊資料行,直接傳回整個NEWS投影,
這作法也是合乎常理的,因為binding就指明要NEWS結構了,
我何必再自行湊資料行呢。
參考資料:
Exeption: The entity or complex type ' ' cannot be constructed in a LINQ to Entities query