Asp.net mvc 实体类型未定义键-代码优先
我不熟悉MVC和实体框架。我搜索了很多,发现了一些类似的问题(例如),但它们并没有解决我的问题Asp.net mvc 实体类型未定义键-代码优先,asp.net-mvc,entity-framework-4,Asp.net Mvc,Entity Framework 4,我不熟悉MVC和实体框架。我搜索了很多,发现了一些类似的问题(例如),但它们并没有解决我的问题 namespace MvcAppInvoice.Models { public class Customer { public int CustomerID { get; set; } public string FirstName { get; set; } public string SurName { get; set; }
namespace MvcAppInvoice.Models
{
public class Customer
{
public int CustomerID { get; set; }
public string FirstName { get; set; }
public string SurName { get; set; }
public virtual CustomerType Type { get; set; }
}
public class CustomerType
{
public int TypeId { get; set; }
public string TypeName { get; set; }
public virtual ICollection<Customer> customers { get; set; }
}
}
namespace mvcappinoice.Models
{
公共类客户
{
public int CustomerID{get;set;}
公共字符串名{get;set;}
公共字符串姓氏{get;set;}
公共虚拟客户类型{get;set;}
}
公共类CustomerType
{
公共int类型ID{get;set;}
公共字符串类型名{get;set;}
公共虚拟ICollection客户{get;set;}
}
}
当我尝试添加控制器时,会出现以下错误:
通常,如果属性名为
Id
或TypeName+Id
,则按照惯例,代码优先隐式地为实体类型设置键。在您的例子中,TypeId
不是它们中的任何一个,因此您应该使用或使用流畅的语法明确地将其标记为key,使用我也有同样的问题。在找到适合我的解决方案之前,我重新启动了项目3次。我手动创建了一个名为UserContext的公共类。当我运行向导添加ADO类时,向导生成了UserContext的部分类。我删除了usercontext类,并修改了VS为我生成的类
namespace UserLayer.Models
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public class UserContext : DbContext
{
public DbSet<UserDetail> UserDetails { get; set; }
}
}
namespace UserLayer.Models
{
使用制度;
使用System.Data.Entity;
使用System.Data.Entity.Infrastructure;
公共类UserContext:DbContext
{
公共DbSet UserDetails{get;set;}
}
}
现在它可能已经在没有修改的情况下工作了。也许删除我的类版本会有用。我不知道。在回顾中,我在尝试添加控制器时遇到了您的错误。我怀疑这是VS2012中的一个bug,因为可以存在同名的分部类和公共类。目的是允许程序员扩展分部类的定义。添加名称空间
using System.ComponentModel.DataAnnotations;
将密钥属性添加到CustomerID
像这样
[Key]
public int CustomerID { get; set; }
然后构建应用程序并尝试添加控制器。这将起作用运行所选代码生成器时出错无法检索未定义键的实体类型的元数据
- 更重要的一点是,sql表只接受[Id],而不接受实体 如果您使用像[MenuId]这样的主键,框架将工作 习惯
- 您应该在模型上添加验证,该模型是键和列顺序
- 列顺序=1,因为在[key]将其增量加1之后 为什么
我希望它能有所帮助。我按照您的建议进行了修改,但即使修改后也会出现相同的错误:请查看有问题的编辑,该编辑应已修复错误。也许你应该重新构建解决方案,让它发挥作用
[Key]
[Column(Order = 1)]
public int RoleIdName { get; set; }