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

  • 相关阅读:
    这 100 道 Python 题,拿去刷!!!
    快速入门 TensorFlow2 模型部署
    零基础入门 Kubernetes,你需要知道这些
    Java 面试必考难点,这一个教程全搞定
    Flask实战:如何从零开发“知乎”
    关于layui表格渲染templet解析单元格的问题
    清除input输入框的历史记录
    phpmyadmin导入导出大数据文件的办法
    yiiaseInvalidCallException The cookie collection is read only.
    Yii2.0关闭自带的debug功能
  • 原文地址:https://www.cnblogs.com/hao-1234-1234/p/8565843.html
Copyright © 2011-2022 走看看