我知道这个问题被问了很多次。我已阅读并实施所有解决方案,但未取得成功。我在使用EF检索数据库中的数据时遇到此错误,并在View上使用此模型后与模型绑定。该操作无法完成,因为DbContext已经使用MVC处理4
我的控制器代码是
using System.Linq;
using System.Web.Mvc;
using JsonRenderingMvcApplication.Models;
namespace JsonRenderingMvcApplication.Controllers
{
public class PublisherController : Controller
{
public ActionResult Index()
{
PublisherModel model = new PublisherModel();
using (DAL.DevelopmentEntities context = new DAL.DevelopmentEntities())
{
model.PublisherList = context.Publishers.Select(x =>
new SelectListItem()
{
Text = x.Name,
Value = x.Id.ToString()
}); ;
}
return View(model);
}
}
}
我的视图代码是
@model JsonRenderingMvcApplication.Models.PublisherModel
@{
ViewBag.Title = "Index";
}
<div>
@Html.DisplayFor(model=>model.Id)
@Html.DropDownListFor(model => model.Id, Model.PublisherList);
</div>
<div id="booksDiv">
</div>
我的模型代码
using System.Collections.Generic;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
namespace JsonRenderingMvcApplication.Models
{
public class PublisherModel
{
public PublisherModel()
{
PublisherList = new List<SelectListItem>();
}
[Display(Name="Publisher")]
public int Id { get; set; }
public IEnumerable<SelectListItem> PublisherList { get; set; }
}
}
我实体的代码是
namespace JsonRenderingMvcApplication.DAL
{
using System;
using System.Collections.Generic;
public partial class Publisher
{
public Publisher()
{
this.BOOKs = new HashSet<BOOK>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Year { get; set; }
public virtual ICollection<BOOK> BOOKs { get; set; }
}
}
是的,这个实体有一个导航属性,但我不想要那个实体数据,所以我不想包含它。
谢谢
什么行会抛出异常? – wdosanjos
@wdosanjos这行“@ Html.DropDownListFor(model => model.Id,Model.PublisherList);”抛出一个异常作为职位的标题 –
虽然没有直接与这个问题联系,但我有相同的错误有趣的发现。我有这个unitOfWork类(具有dbcontext对象)和类ABC。 ABC类通过unitOfWork类使用dbContext对象。 ABC类和unitOfWork类都通过windsor城堡DI容器得到实例化。我得到了非常相同的错误,问题是我在DI容器的初始化过程中注册了ABC类。我写过代码,如Register(Component.For().ImplementedBy ()**。LifeStyle.Transient **)我错过了粗体代码以结束这个问题。 –
RBT