我正在尝试学习使用ASP.NET MVC 5和实体框架构建一个简单的应用程序。我能够添加迁移并更新数据库。我的应用程序在执行时运行良好。下面是我的应用程序的以下代码。
CustomersController:
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; }
}
}
CustomersView:
@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”上下文已更改 创建。考虑使用代码优先迁移来更新数据库 (http://go.microsoft.com/fwlink/?LinkId=238269)。'
var客户= _context.Customers.Include(c => c.MembershipType).ToList();
异常图片:
通过将目标数据库更新到DBContext,甚至可以从PackageManagerConsole中使用实体框架进行检查。甚至我都经历过StackOverflow System.InvalidOperationException中的一些旧线程。但这对我不起作用。有人可以帮忙吗?
答案 0 :(得分:0)
(由于某种原因)您的数据库模型与您的模型不同步。
您可以尝试在程序包管理器控制台add-migration test
中运行,看看它是否会产生新的迁移。如果是这样,您只需在此之后运行update-database
。
如果这没有帮助,请检查以下答案:The model backing the 'DataContext' context has changed since the database was created