将IEnumerable模型对象转换为数组。
将IEnumerable模型对象转换为数组。
我正在学习C#和dotnet core,因为我想从PHP转向使用它们来开发我的Web应用程序。我在这里遇到了一个具体的问题,我无法理解解决方法。
我将在下面展示所有的代码,但是在此之前,我想先概述一下我的目标:我正在从SQL数据库中获取一个表。我可以使用foreach循环在我的页面上完整地显示这个表。然而,当我尝试将结果转换为数组,以便我可以访问返回表中的特定项时,我遇到了各种错误。
顺便提一下,我在Udemy的学习课程中使用这个教程作为辅助学习资料:
https://docs.efproject.net/en/latest/platforms/aspnetcore/existing-db.html
可能值得一提的是,我是根据上述链接教程中的现有数据库进行的模型逆向工程。
下面是我的文件,我将在下面解释错误:
Model:
namespace ASPNET_Core_1_0.Models { public partial class Graph { public int AutoId { get; set; } public int Numbers { get; set; } } }
ModelContext:
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; namespace ASPNET_Core_1_0.Models { public partial class GraphsContext : DbContext { public virtual DbSetGraph { get; set; } public GraphsContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity (entity => { entity.HasKey(e => e.AutoId) .HasName("PK_Blog"); }); } } }
Controller:
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; // 更多关于启用空项目的MVC的信息,请访问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()); } } }
在微软的教程中,Index视图使用了ToList()方法:
public IActionResult Index() { return View(_context.Graph.ToList()); }
我将它更改为ToArray(),希望它能像一个数组一样工作 :/
Index View
@model IEnumerable
@{
ViewBag.Title = "Graphs";
}
Graphs
Id | Numbers |
---|---|
@Html.DisplayFor(modelItem => item.AutoId) |
@Html.DisplayFor(modelItem => item.Numbers) |
@{
// int[] arr = Model.ToArray();
// int[] array = Model.Cast
// int somenumber = array[5];
}
@Html.DisplayForModel(Model)
问题:
如果你看一下我的index视图,你会发现有三行被注释掉的代码,我试图将Model对象转换为数组,以便我可以独立地访问返回表中的每个项目。
当我运行这个项目时,我得到了一个错误:
在处理请求时发生了一个未处理的异常。
InvalidCastException: 无法将类型为"ASPNET_Core_1_0.Models.Graph"的对象强制转换为类型"System.Int32"。
问题:
我如何将Model对象转换为数组,以便我可以显示表中特定的项,而不是整个表。
比如说,我想返回ID为4的Value字段?
我明白这很可能是一个新手问题,但我真的很难获得或理解我在网上看到的答案。
表数据
我的表数据是一个简单的两列键值对。ID号和对应的值。
ID Value 1 10 2 20 3 30 4 40 5 50
等等
研究
https://www.tutorialspoint.com/csharp/csharp_arrays.htm
https://www.dotnetperls.com/array
问题的原因是代码中出现了将一个IEnumerable类型的Model对象转换为数组的操作。解决方法是使用LINQ的Select方法选择需要的值并转换为数组,或者直接在已有的数组中获取指定的值。
具体解决方法如下:
1. 使用LINQ的Select方法选择需要的值并转换为数组:
int[] array = Model.Select(g => g.Numbers).ToArray();
2. 在已有的数组中获取指定的值:
int value = Model.ToArray()[0].Numbers;
需要注意的是,一个Graph不仅仅是一个int,它是一个包含int的对象。因此在获取值时需要注意对象的结构。
另外,需要注意的是,在输出值时使用的`Html.DisplayText()`方法可能并不会产生预期的效果,可以尝试直接将值输出到页面上。