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

  • 相关阅读:
    POJ 3694 Network (求桥,边双连通分支缩点,lca)
    UVA 796
    UVA 315 315
    POJ 1236 Network of Schools (有向图的强连通分量)
    【转】有向图强连通分量的Tarjan算法
    HDU 3072 Intelligence System (强连通分量)
    【转】强大的vim配置文件,让编程更随意
    WORDPRESS登录后台半天都无法访问或者是访问慢的解决方法
    phpstorm+Xdebug断点调试PHP
    PHP性能调优---PHP调试工具Xdebug安装配置教程
  • 原文地址:https://www.cnblogs.com/hao-1234-1234/p/8565843.html
Copyright © 2011-2022 走看看