無法將類型“System.Collections.Generic.List<anonymous type:string ClassID,string ClsssName>”隱式轉換為“System.Collections.Generic.List<Ecology.Model.EnergyFlowGraph>”
一、EF應用中,常見類型轉換問題解決方案
public List<EnergyFlowGraph> GetData() { var data = db.EnergyFlowGraph.Select(d => new { ClassID = d.ClassID, ParentClassID = d.ParentClassID, ClassName = d.ClassName, }).ToList(); return data; //報錯: 無法將類型“System.Collections.Generic.List<anonymous type:string ClassID,string ClsssName>”隱式轉換為“System.Collections.Generic.List<Ecology.Model.EnergyFlowGraph>” // 根據提示可知錯誤的原因 匿名類型anonymous type //d => new EnergyFlowGraph //解決方案一: new EnergyFlowGraph //var data = db.EnergyFlowGraph.Select(d => new EnergyFlowGraph //{ // ClassID = d.ClassID, // ParentClassID = d.ParentClassID, // ClassName = d.ClassName, //}).ToList(); //return data; //解決方案二:foreach遍歷 //var list = new List<EnergyFlowGraph>(); //foreach (var temp in data) //{ // var energyFlowGraph = new EnergyFlowGraph(); // energyFlowGraph.ClassID = temp.ClassID; // energyFlowGraph.ClassName = temp.ClassName; // energyFlowGraph.ParentClassID = temp.ParentClassID; // list.Add(energyFlowGraph); //} //return list; }
二、model類
namespace Ecology.Models { using System; using System.Collections.Generic; public partial class EnergyFlowGraph { public string ClassID { get; set; } public string ParentClassID { get; set; } public string ClassName { get; set; } } }
三、測試結果
1、 經測,方案一失敗,方案二成功。
2、有些情況下我們會專門為視圖View(MVC)建一個視圖類,已整合我們想要的數據。一般名稱會區別於原始類名稱。