0

I am learning C# and dotnet core as I want to move away from PHP for my web apps. I am having a specific problem here and I can't get my head around it.

I will show you all the code below, but here is a summary of what I want to achieve: I am getting a table from SQL database. I can display the table in full on my page using foreach loop. However when I am trying to convert the result into an array so I can access a specific item from the returned table I get into all sorts of errors.

By the way I was using this tutorial to supplement my Udemy learning course: https://docs.efproject.net/en/latest/platforms/aspnetcore/existing-db.html

Might be worth mentioning that I was reverse engineering the Models from existing database (as it is in the linked tutorial above)

Here are my files, I'll explain errors below:

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 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");
            });
        }
    }
}

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;

// 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());
        }

    }
}

In MS tutorial the Index view used ToList() method:

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

I changed it to ToArray() in hope it will behave like one :/

Index View

@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>

The problem:

If you look at my index view, there are three commented out lines where I was trying to cast the Model object to array so I could access each item in the returned table independently.

Upon running the project I am getting an error:

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'.

Question: How can I get Model object into an array so I can display specific item from the table instead of the whole table.

Say I want to return Value field for ID 4?

I understand this most likely is a rookie question, but I am having real trouble getting or even understanding the answers I see online.

Table data

My table data is simple two column key -> value pair. ID number and corresponding value.

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

ect

Research

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

Community
  • 1
  • 1
PawelKosi
  • 151
  • 1
  • 3
  • 13
  • Which line of code is throwing the exception? – Robert Harvey Nov 04 '16 at 18:20
  • `int[] array = Model.Cast().ToArray();` the middle line of the commented out lines in the view – PawelKosi Nov 04 '16 at 18:21
  • It appears that you're trying to cast a `Graph` object to `int`, or whatever is in the `Graph` property of your model to `int` Is that possible? – Robert Harvey Nov 04 '16 at 18:22
  • A `Graph` is not an `int`. It's an object. Which `int` *from* that object are you trying to use? – David Nov 04 '16 at 18:23
  • This is what I am trying to get my head around. The graph object is just the table from the database? Or am I completely on the wrong track here – PawelKosi Nov 04 '16 at 18:24
  • It's either the table from the database, or a tuple from that table in the database. Neither will cast to an `int`. To get an `int` you need to refer to a column or field in your `Graph` object that corresponds to an `int`. – Robert Harvey Nov 04 '16 at 18:24
  • Hey Robert, thanks it just shows that I do not understand what I am dealing with here. – PawelKosi Nov 04 '16 at 18:25
  • Well, you need to think carefully about what you are doing, and specify what it is that you want to do (your intent) in your code. I'm not sure copy/paste programming is going to work here. – Robert Harvey Nov 04 '16 at 18:26
  • @RobertHarvey I am trying to learn. At the moment the copying and pasting code from different tutorials is all I can do. I do struggle with understanding some basic concepts, but the best way for me to learn is by trying. Once I fiddle with code I can move to trying to build something myself. As you can see by the way I am not asking anyone here for help with my work project (OMG help me with X or my boss is going to kill me) but with understanding - however basic - concepts. – PawelKosi Nov 04 '16 at 18:47
  • If you want to display a specific object, it should be filtered in the controller (or better in the database) and the view should receive only that object. – Phil1970 Nov 05 '16 at 03:39

2 Answers2

2

You have an array of Graph objects, not an array if ints. If all you want is the array of Numbers values from those graphs, you can select it:

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

Or, to get a specific number from the array you already have:

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

A Graph is more than just an int. It's an object which contains ints.

David
  • 208,112
  • 36
  • 198
  • 279
  • I am just putting this in and will report back in a sec! In any case thank you for lightning fast response. – PawelKosi Nov 04 '16 at 18:32
  • Hey David, I have put the `int value = Model.ToArray()[0].Numbers;` in the view and then tried to output it with `@Html.DisplayText(value.ToString());` - no errors this time, however nothing displays. – PawelKosi Nov 04 '16 at 18:41
  • 1
    @PawelKosi: I don't think `Html.DisplayText()` does what you expect it to do. What happens if you just emit `@value` to the page? – David Nov 04 '16 at 18:46
  • Yes! Thank you for taking time to help a learner. With this I can speed up my learning, now I know where there are blatant holes in my understanding. Accepted answer and +1 – PawelKosi Nov 04 '16 at 18:52
0

Your model is type of IEnumerable<ASPNET_Core_1_0.Models.Graph> so you cannot parse it to int - this is the root cause of exception.

To display specific value from an array you can write:

@{
    int specificItemValue = Model[5].Numbers;
}
Fka
  • 6,044
  • 5
  • 42
  • 60