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

  • 相关阅读:
    oracleDBA-D4
    oracleDBA-D3
    oracleDBA-D2
    大数据架构学习记录
    UBUNTU 安装最新版 nodejs
    datax 单条记录超过大小限制,当前限制为:67108864
    将anaconda中已存在的虚拟环境增加到jupyterlab
    jupyter 启动python3 内核 总是出现错误 ImportError: cannot import name 'create_prompt_application'
    CDH 本地hadoop支持读写 AWS S3a
    hadoop 集群集成jupyterhub 出现的问题
  • 原文地址:https://www.cnblogs.com/hao-1234-1234/p/8565843.html
Copyright © 2011-2022 走看看