EntityCommandExecutionException未处理
我正在使用EF 4.1 MVC3编写应用程序。 我正在尝试在它上面实现CRUD。 问题是,当我尝试实现第一个索引页面时,它给了我一个错误。 我正在使用中央服务器的外部数据库。 我只是在尝试一个简单的注册表单。 我有第一个模型类RegModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Registration.Models { public class Register { public int Id { get; set; } public string UserName { get; set; } public string Password { get; set; } public string Email { get; set; } public string Address { get; set; } } }
然后是RegModelContext.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Registration.Models { public class Register { public int Id { get; set; } public string UserName { get; set; } public string Password { get; set; } public string Email { get; set; } public string Address { get; set; } } }
我的控制器名称是RegController.cs(我只是试图首先实现Index。)在控制器中。 当我执行我的应用程序时它return View(db.Registrant.ToString());
上的错误return View(db.Registrant.ToString());
“entitycommandexecutionexception未处理”“执行命令定义时发生错误。有关详细信息,请参阅内部exception。”
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Registration.Models; using System.Configuration; namespace Registration.Controllers { public class RegController : Controller { // // GET: /Reg/ private string CmdStr = ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString; public ActionResult Index() { using (var db = new RegModelContext(CmdStr)) { return View(db.Registrant.ToString()); } } } }
然后通过使用索引我为索引创建视图(Index.cshtml):
@model IEnumerable @{ Layout = null; } Index @Html.ActionLink("Create New", "Create")
UserName Password Email Address @foreach (var item in Model) { @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | @Html.ActionLink("Details", "Details", new { id=item.Id }) | @Html.ActionLink("Delete", "Delete", new { id=item.Id }) @item.UserName @item.Password @item.Email @item.Address }
我正在使用这个web.config文件
问题出在这个代码上:
string CmdStr = ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString; using (var db = new RegModelContext(CmdStr)) { return View(db.Registrant.ToString()); }
首先,您不需要显式指定连接字符串。 按照惯例,entity framework将在web.config文件中查找匹配的连接字符串。 只需确保连接字符串的名称与DbContext的名称相匹配。
其次,您通过db.Registrant
访问数据库中的Register
对象db.Registrant
。 在它上面调用ToString()
没有任何意义。
您的视图需要一个Registration.Models.Register
列表而不是字符串。 将您的代码更改为:
using (var db = new RegModelContext()) { return View(db.Registrant.ToList()); }
请注意,这将返回数据库中的所有Register
项。 这可能是一大堆数据。 也许你想实现分页或其他类型的过滤,以确保一切按预期工作。