【问题标题】:IEnumerable Model Object into ArrayIEnumerable 模型对象转换为数组
【发布时间】:2017-03-18 16:25:38
【问题描述】:

我正在学习 C# 和 dotnet 核心,因为我想为我的 Web 应用程序摆脱 PHP。我在这里遇到了一个特定的问题,我无法理解它。

我将向您展示下面的所有代码,但这里是我想要实现的摘要:我正在从 SQL 数据库中获取一个表。我可以使用 foreach 循环在我的页面上完整显示表格。但是,当我尝试将结果转换为数组以便可以从返回的表中访问特定项目时,我会遇到各种错误。

顺便说一下,我使用本教程来补充我的 Udemy 学习课程: https://docs.efproject.net/en/latest/platforms/aspnetcore/existing-db.html

可能值得一提的是,我正在从现有数据库中对模型进行逆向工程(如上面链接的教程中所示)

这是我的文件,我将在下面解释错误:

型号:

namespace ASPNET_Core_1_0.Models
{
    public partial class Graph
    {
        public int AutoId { get; set; }
        public int Numbers { get; set; }
    }

}

模型上下文:

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace ASPNET_Core_1_0.Models
{
    public partial class GraphsContext : DbContext
    {
        public virtual DbSet<Graph> Graph { get; set; }


        public GraphsContext(DbContextOptions<GraphsContext> options)
            : base(options)
        { }


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Graph>(entity =>
            {
                entity.HasKey(e => e.AutoId)
                    .HasName("PK_Blog");
            });
        }
    }
}

控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ASPNET_Core_1_0.Models;
using Microsoft.EntityFrameworkCore;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace ASPNET_Core_1_0.Controllers
{
    public class GraphsController : Controller
    {
        private GraphsContext _context;

        public GraphsController(GraphsContext context)
        {
            _context = context;
        }

        public IActionResult Index()
        {
            return View(_context.Graph.ToArray());
        }

        public IActionResult GraphJ()
        {
            var graphs = _context.Graph.FromSql("SELECT * FROM dbo.Graph").ToList();
            ViewBag.YourHtml = graphs;

            return View(_context.Graph.ToList());
        }

    }
}

在 MS 教程中,Index 视图使用了 ToList() 方法:

    public IActionResult Index()
    {
        return View(_context.Graph.ToList());
    }

我将其更改为 ToArray(),希望它的行为类似于:/

索引视图

@model IEnumerable<ASPNET_Core_1_0.Models.Graph>

@{
    ViewBag.Title = "Graphs";
}

<h2>Graphs</h2>



<table class="table">
    <tr>
        <th>Id</th>
        <th>Numbers</th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.AutoId)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Numbers)
            </td>
        </tr>
    }
</table>

@{ 

    // int[] arr = Model.ToArray();

    // int[] array = Model.Cast<int>().ToArray();
    // int somenumber = array[5];
}

<div class="row">
    <div class="col-md-12 text-center">
        @Html.DisplayForModel(Model)
        <br />

    </div>
</div>

问题:

如果您查看我的索引视图,我会在其中尝试将 Model 对象转换为数组的三个注释掉的行,以便我可以独立访问返回表中的每个项目。

运行项目时出现错误:

处理请求时发生未处理的异常。

InvalidCastException:无法转换类型的对象 'ASPNET_Core_1_0.Models.Graph' 输入'System.Int32'。

问题: 如何将 Model 对象放入数组中,以便显示表格中的特定项目而不是整个表格。

假设我想返回 ID 4 的值字段?

我知道这很可能是一个菜鸟问题,但我很难获得甚至理解我在网上看到的答案。

表格数据

我的表数据是简单的两列键 -> 值对。 ID 号和对应的值。

ID Value
1  10
2  20
3  30
4  40
5  50 

研究

Best way to convert IList or IEnumerable to Array

Convert IEnumerable<int> to int[]

Error: "Cannot implicitly convert type"

C# - Cannot implicitly convert type List<Product> to List<IProduct>

https://www.tutorialspoint.com/csharp/csharp_arrays.htm

https://www.dotnetperls.com/array

https://www.dotnetperls.com/list

How can I find a specific element in a List<T>?

Getting an item in a list

Getting a list item by index

Get array item based on index

【问题讨论】:

  • 哪行代码抛出异常?
  • int[] array = Model.Cast&lt;int&gt;().ToArray(); 视图中被注释掉的行的中间行
  • 您似乎正在尝试将Graph 对象转换为int,或者您模型的Graph 属性中的任何内容转换为int 这可能吗?
  • Graph 不是int。它是一个对象。您尝试使用哪个int 来自该对象?
  • 这就是我想要解决的问题。图形对象只是数据库中的表?还是我完全走错了路

标签: c# arrays asp.net-core asp.net-core-mvc .net-core


【解决方案1】:

您有一个 Graph 对象数组,而不是 ints 的数组。如果您想要的只是这些图中的 Numbers 值数组,您可以选择它:

int[] array = Model.Select(g => g.Numbers).ToArray()

或者,从您已有的数组中获取特定数字:

int value = Model.ToArray()[0].Numbers

Graph 不仅仅是int。这是一个包含 ints 的对象。

【讨论】:

  • 我只是把它放进去,稍后会报告!无论如何,感谢您闪电般的快速响应。
  • 嘿,David,我已将 int value = Model.ToArray()[0].Numbers; 放入视图中,然后尝试使用 @Html.DisplayText(value.ToString()); 输出它 - 这次没有错误,但没有显示任何内容。
  • @PawelKosi:我不认为Html.DisplayText() 做你期望它做的事情。如果您只是向页面发出 @value 会发生什么?
  • 是的!感谢您花时间帮助学习者。有了这个,我可以加快我的学习速度,现在我知道我的理解哪里有明显的漏洞。接受的答案和 +1
【解决方案2】:

您的模型类型为 IEnumerable&lt;ASPNET_Core_1_0.Models.Graph&gt;,因此您无法将其解析为 int - 这是异常的根本原因。

要显示数组中的特定值,您可以编写:

@{
    int specificItemValue = Model[5].Numbers;
}

【讨论】:

  • 让我试一试,我会报告的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-27
  • 2013-03-25
  • 1970-01-01
相关资源
最近更新 更多