c# - 出现错误:System.InvalidOperationException:用户未处理
问题描述
我正在尝试学习使用 ASP.NET MVC 5 和实体框架来构建一个简单的应用程序。我能够添加迁移并更新数据库。我的应用程序在执行时工作正常。下面是我的应用程序的以下代码。
客户控制器:
using System.Linq;
using System.Web.Mvc;
using WebChatApp.Models;
using System.Data.Entity;
namespace WebChatApp.Controllers
{
public class CustomersController : Controller
{
private ApplicationDbContext _context;
public CustomersController()
{
_context = new ApplicationDbContext();
}
protected override void Dispose(bool disposing)
{
_context.Dispose();
}
// GET: Customers
public ViewResult Index()
{
var customers = _context.Customers.Include(c => c.MembershipType).ToList();
return View(customers);
}
public ActionResult Details(int id)
{
var customer = _context.Customers.SingleOrDefault(c => c.Id == id);
if (customer == null)
return HttpNotFound();
return View(customer);
}
}
}
楷模 :
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace WebChatApp.Models
{
public class Customer
{
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
public bool IsSubscribedToNewsletter { get; set; }
public MembershipType MembershipType { get; set; }
public byte MembershipTypeId { get; set; }
}
}
客户视图:
@model IEnumerable<WebChatApp.Models.Customer>
@{
ViewBag.Title = "Customers";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Customers</h2>
@if (!Model.Any())
{
<p>We don't have any customer yet.</p>
}
else
{
<table class=" table table-bordered table-hover">
<thead>
<tr>
<th>Customer</th>
<th>Membership Type</th>
</tr>
</thead>
<tbody>
@foreach (var customer in Model)
{
<tr>
<td>@Html.ActionLink(customer.Name, "Details","Customers", new { id = customer.Id }, null)</td>
<td>@customer.MembershipType.Name</td>
</tr>
}
</tbody>
</table>
}
迁移:
SQL 服务器中的表:
当我尝试执行执行并从 NavBar 导航到客户模块时,出现以下错误。
System.InvalidOperationException:'支持'ApplicationDbContext'上下文的模型自数据库创建以来已更改。考虑使用 Code First 迁移来更新数据库 ( http://go.microsoft.com/fwlink/?LinkId=238269 )。
var customers = _context.Customers.Include(c => c.MembershipType).ToList();
异常图像:
即使我通过将目标数据库更新到 DBContext 来检查 PackageManagerConsole 中的实体框架。即使我已经经历了 StackOverflow System.InvalidOperationException中的一些旧线程。但它对我不起作用。任何人都可以帮忙吗?
解决方案
您的数据库模型(出于某种原因)与您的模型不同步。您可以尝试在包管理器控制台中运行:add-migration test
看看它是否会产生新的迁移。如果是这样,您只需在update-database
此之后运行。
如果这没有帮助,请检查以下答案:支持“DataContext”上下文的模型自创建数据库以来已更改
推荐阅读
- ios - 在 iOS 中的 firebase 数据库中查询
- elasticsearch - 如何通过 HTTP/REST API 调用在 elasticsearch 中使用数据
- javascript - LinkedIn OAuth:请求授权令牌
- spring - 如何让spring管理匿名类的线程
- ajax - 关闭 mondal 后刷新主视图(单击按钮或外部)
- mysql - 如何为 mysql 添加值:端口的空值
- r - Dplyr groupby 名称和最近 n 个事件的滚动平均值(按日期)
- php - 在 PHP 中使用数组值进行计算
- webpack - Webpack 4 中每个条目的多个目标
- cors - 澄清哪些请求使用 CORS