[英]Selecting only specific columns using IQueryable in asp.net mvc
我是asp.net mvc的新手。 我目前正在使用由另一個人開發的代碼,但最終陷入僵局。
IQueryable<DatatableTrainingHistory> trainingView = (from b in db.DatatableTrainingHistorys
select b);
/* Returns the format needed to output DataTable extension */
return DataTablesResult.Create(trainingView, dataTableParam, uv => new
{
//stuff runs here
});
該代碼的作用是從表的所有列中選擇數據。 我目前需要的是代碼選擇特定的列,例如TrainingName
, TrainingTime
, Location
和Quota
。 輸出必須是IQueryable
類型,因為代碼使用此擴展名來輸出數據。
我嘗試了多種方法來解決此問題。
(1)
IQueryable<DatatableTrainingHistory> trainingView = (from b in db.DatatableTrainingHistorys
select new DatatableTrainingHistory
{
TrainingName = b.TrainingName,
TrainingTime = b.TrainingTime,
Quota = b.Quota,
Location = b.Location,
});
上面的代碼輸出錯誤:
The entity or complex type 'AppModel.DatatableTrainingHistory' cannot be constructed in a LINQ to Entities query.
(2)
IQueryable<DatatableTrainingHistory> trainingView = (from b in db.DatatableTrainingHistorys
select new
{
TrainingName = b.TrainingName,
TrainingTime = b.TrainingTime,
Quota = b.Quota,
Location = b.Location,
}).AsQueryable();
上面的代碼顯示了一條錯誤消息:
Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Linq.IQueryable<Project.Models.DatatableTrainingHistory>'. An explicit conversion exists (are you missing a cast?)
誰能指出我正確的方向? 謝謝。
(1)。 DatatableTrainingHistory
是一個實體對象,您根本無法在LINQ查詢中使用實體對象。
(2)。 您要返回anonymous object
,因此應使用var
var trainingView = (from b in db.DatatableTrainingHistorys
select new
{
TrainingName = b.TrainingName,
TrainingTime = b.TrainingTime,
Quota = b.Quota,
Location = b.Location,
}).AsQueryable();
有兩種可能的解決方案:
他們兩個都有優點和缺點 ,第二個解決方案需要付出更多的努力,但是它將為您提供強類型=>更少的錯誤。 有幾個庫可以為您自動進行對象映射(例如: AutoMapper
),也許您可以嘗試一下。
干杯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.