'Error displaying info from 2 linked tables using Entity Framework Core
I am following a tutorial and getting an error that the tutorial doesn't when trying to use the foreign key to pull data from a second table to display in my MVC display. I am using the following code, and get the following error. Can anyone help point me in the right direction as I cant see anything wrong.
System.InvalidOperationException: 'There is already an open DataReader associated with this Connection which must be closed first.'
This exception was originally thrown at this call stack:
[External Code] InAndOut.Controllers.ExpenseController.Index() in ExpenseController.cs [External Code]
Code:
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using InAndOut.Data;
using InAndOut.Models;
using InAndOut.Models.ViewModels;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace InAndOut.Controllers
{
public class ExpenseController : Controller
{
private readonly ApplicationDbContext _db;
public ExpenseController(ApplicationDbContext db)
{
_db = db;
}
public IActionResult Index()
{
IEnumerable<Expense> objList = _db.Expenses;
foreach (var obj in objList)
{
obj.ExpenseType = _db.ExpenseTypes.FirstOrDefault(u => u.Id == obj.ExpenseTypeId);
}
return View(objList);
}
//Get-Create
public IActionResult Create()
{
ExpenseVM expenseVm = new ExpenseVM()
{
Expense = new Expense(),
TypeDropDown = _db.ExpenseTypes.Select(i => new SelectListItem
{
Text = i.Name,
Value = i.Id.ToString()
})
};
return View(expenseVm);
}
//Post-Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(ExpenseVM obj)
{
if (ModelState.IsValid)
{
//obj.ExpenseTypeId = 3;
_db.Expenses.Add(obj.Expense);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(obj);
}
//Get Delete
public IActionResult Delete(int? id)
{
if (id == null || id == 0)
{
return NotFound();
}
var obj = _db.Expenses.Find(id);
if (obj == null)
{
return NotFound();
}
return View(obj);
}
//Post-Delete
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult DeletePost(int? id)
{
var obj = _db.Expenses.Find(id);
if (obj == null)
{
return NotFound();
}
_db.Expenses.Remove(obj);
_db.SaveChanges();
return RedirectToAction("Index");
}
//Get Update
public IActionResult Update(int? id)
{
if (id == null || id == 0)
{
return NotFound();
}
var obj = _db.Expenses.Find(id);
if (obj == null)
{
return NotFound();
}
return View(obj);
}
//Post-Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Update(Expense obj)
{
if (ModelState.IsValid)
{
_db.Expenses.Update(obj);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(obj);
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
