【发布时间】:2017-06-08 01:35:33
【问题描述】:
我是 MVC 的新手,我完全被模型验证异常卡住了。
我想使用实体框架从数据库表中检索数据。我使用 Visual Studio 2012 和 Sqlexpress 作为数据库服务器。这是我到目前为止所做的
现在我总是在 MobileContorller 类中得到模型验证异常。即使我为表和模型提供了相同的列名。我无法弄清楚究竟是什么导致了这个异常。 Table Mobiles 是
模型 int NotNull 键入 nchar(10) NotNull 成本 nchar(10) NotNull
为了方便起见,我考虑了成本。 手机模型类
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Mvcpractice4.Models
{
[Table("Mobiles")]
public class Mobile
{ public int Model { get; set; }
public string Type { get; set; }
public String Cost { get; set; }
}
}
MobilesContorller
namespace Mvcpractice4.Controllers
{
public class MobilesController : Controller
{
public ActionResult Details(int id)
{
MobilesContext pc = new MobilesContext();
List<Mobile> plist = pc.productsproperty.ToList();
return View(plist);
}
}
}
MobilesContext 类
namespace Mvcpractice4.Models
{
public class MobilesContext:DbContext
{
public DbSet<Mobile> productsproperty { get; set; }
}
}
详情查看
@model IEnumerable< Mvcpractice4.Models.Mobile>
@using Mvcpractice4.Models;
@{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<ul>@foreach(Mobile obj in @Model)
{
<li>
@obj.Model
</li>
<li>
@obj.Type
</li>
<li>
@obj.Cost
</li>
}
</ul>
而Web.Cofig文件中的连接字符串为
<connectionStrings>
<add name="MobilesContext" connectionString="server=.\sqlexpress;database=Gadgets;integrated Security=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
【问题讨论】:
-
您得到的确切错误是什么?
-
代码中何时何地出现异常?
-
只有当您尝试将无效实体保存到数据库时才会引发此类异常。但是,就此而言,您发布的任何代码都不会尝试保存任何实体,甚至不会处理发布数据。发布实际引发异常的代码。
-
在 MobilesController 类中。我在 ToList() 处收到“用户代码未处理 ModelValidation 异常”;方法。
标签: asp.net-mvc entity-framework model-view-controller