0

I'm doing some tests to take a project. I have been working with ASP.NET Core MVC and Entity Framework relatively recently. I have a simple database in SQL Server to prove how it is:

enter image description here

In the test project I have a controller TestController; the code is this:

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

namespace WEBAPPHTTP.Controllers
{
    [Route ("api/controller[]")]
    public class TestController: Controller
    {
        [HttpGet("/api/values")]
        public IEnumerable<string> Get()
        {
            using (TareasContext db = new TareasContext())
            {
                var listar = db.Tareas;
                var n = listar.Count();

                string[] array = new string[n+1];
                int i = 0;
                foreach (var otareas in listar)
                {
                    array[i] = otareas.Tarea.ToString();
                    i = i++;
                }

                return array;
            }
        }
    }
}

Obviously I'm doing something wrong but the output is this:

in localhost/api/values:

["ahora",null,null,null,null]

It only shows me the last record of the database followed by a few NULL, this test the idea is that all the results are loaded in the array.

I'm sure it's a very early mistake, I hope you can guide me.

1
  • i = i++; looks very strange and wrong. You assign i to i and then increment i. Commented Feb 2, 2019 at 18:01

2 Answers 2

2

I dont know what you want to do after this, but if you just want to list out your items, you should be able to do something like this:

using (TareasContext db = new TareasContext())
        {
            return db.Tareas.ToList();

        }

That will give you the full list with all items in it with all properties, if you want just a part of your properties I would suggest to do a .Select as well. Remember to do a where as well so you dont always return the full list (if it gets enourmus big)

Peace!

Sign up to request clarification or add additional context in comments.

Comments

2

You code is not efficient. This is the much cleaner version that does the same:

using (TareasContext db = new TareasContext())
{
    var result = db.Tareas.Select(x => x.Tarea).ToList();
    return result;
}

As I see the Tarea column is of varchar or nvarchar type. So, you don't need to cast it to string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.