使用实体框架核心显示来自2个链接表的信息错误



我正在遵循一个教程,并得到一个错误,该教程不试图使用外键从第二个表拉数据显示在我的MVC显示。我正在使用以下代码,并得到以下错误。我看不出有什么不对的地方,谁能给我指个方向吗?

系统。InvalidOperationException: '已经有一个打开的数据读取器与此连接相关联,必须先关闭。'

这个异常最初是在这个调用堆栈中抛出的:

[外部代码]InAndOut.Controllers.ExpenseController.Index() in ExpenseController.cs[外部代码]

代码:

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

你可以修改你的代码:

var objList = _db.Expenses.ToArray();
for (var i = 0; i < objList.Length ; i++) {
objList[i].ExpenseType = _db.ExpenseTypes.FirstOrDefault(u => u.Id ==  objList[i].ExpenseTypeId);
}

但我猜你也可以试试这个方法:

var objList = _db.Expenses.Include(e=> e.ExpenceType).ToArray();

最新更新