IEnumerable 模型对象到数组

IEnumerable Model Object into Array

我正在学习 C# 和 dotnet 核心,因为我想摆脱 PHP 的网络应用程序。我在这里遇到了一个具体问题,我无法解决这个问题。

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

顺便说一下,我使用本教程来补充我的 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 教程中,索引视图使用了 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>

问题:

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

在 运行 项目上我收到一个错误:

An unhandled exception occurred while processing the request.

InvalidCastException: Unable to cast object of type 'ASPNET_Core_1_0.Models.Graph' to type 'System.Int32'.

问题: 如何将模型对象放入数组中,以便显示 table 中的特定项目而不是整个 table.

假设我想要 return ID 4 的值字段?

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

Table数据

我的 table 数据是简单的两列键 -> 值对。身份证号码和对应的值。

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

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

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

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

您有一个 Graph 个对象的数组,而不是 int 个对象的数组。如果你想要的只是来自这些图表的 Numbers 值的数组,你可以 select 它:

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

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

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

A Graph 不仅仅是 int。这是一个 包含 ints.

的对象