无法将类型“System.Collections.Generic.List<anonymous type:string ClassID,string ClsssName>”隐式转换为“System.Collections.Generic.List<Ecology.Model.EnergyFlowGraph>”

无法将类型“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)建一个视图类,已整合我们想要的数据。一般名称会区别于原始类名称。

 

posted @ 2018-03-14 10:41  hao_1234_1234  阅读(2777)  评论(0编辑  收藏  举报