实体框架代码优先方法和ModelValidationException [英] Entity Framework Code-First Aproach and ModelValidationException
问题描述
我正在构建MVC应用程序,并在构建实体和数据库时尝试使用代码优先的方式.
I'm building an MVC application and trying to use code-first aproach while building entities and database.
运行代码时得到ModelValidationException
. (消息: System.Data.Entity.ModelConfiguration.ModelValidationException'发生在EntityFramework.dll中,但未在用户代码中处理)
I get ModelValidationException
when I run code. (Message: System.Data.Entity.ModelConfiguration.ModelValidationException' occurred in EntityFramework.dll but was not handled in user code)
这是代码:
控制器:
public class HomeController : Controller {
PhonesDB _db = new PhonesDB();
public ActionResult Index() {
var model = from b in _db.ProductList //Exception appears here
select b;
return View(model);
}
}
模型:
namespace SmartPhoneCatalog.Models {
public class Products {
public int ProductID { get; set; }
public string Manufacturer { get; set; }
public string Name { get; set; }
//...
}
}
namespace SmartPhoneCatalog.Models {
public class PhonesDB:DbContext {
public DbSet<Products> ProductList { get; set; }
}
}
这是视图:
@model IEnumerable<SmartPhoneCatalog.Models.Products>
@{
ViewBag.Title = "Home";
}
@foreach (var item in Model) {
<div>
<h4>@item.Name</h4>
<div>@item.Price</div>
<hr/>
</div>
}
我想念什么吗?
试图先启动空的mvc应用程序,然后再启动模板,但两者都存在相同的问题.
Tried starting empty mvc application and then template but had the same problem on both one.
用var model = _db.ProductList.ToList();
替换LINQ并没有帮助.还尝试编辑PhonesDB
模型(更改为粗体):
Replacing LINQ with var model = _db.ProductList.ToList();
didn't help. Also tried editing PhonesDB
model(changes are in bold):
public **partial** class PhonesDB : DbContext {
public PhonesDB():**base("PhonesDB")**{
}
**protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}**
public DbSet<Products> ProductList { get; set; }
}
仍然出现相同的异常. 有任何解决方法的想法吗?
still getting same exception. Any ideas how to fix it?
推荐答案
该异常似乎隐藏了真正的异常.我的猜测是,由于您的ProductId字段上没有[Key]属性,因此引发了真正的异常:
That exception looks to be hiding the real exception. My guess is that the real exception is being thrown because you don't have a [Key] attribute on your ProductId field:
public class Products {
[Key]
public int ProductID { get; set; }
public string Manufacturer { get; set; }
public string Name { get; set; }
//...
}
此处是有关Code First使用的属性的更多信息
Here is some more info about the attributes used by Code First
这篇关于实体框架代码优先方法和ModelValidationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!