[英]Model validation error: EntityType has no key defined. Define the key for this EntityType
I changed an attribute of my model from string
to CultureInfo
, and am now getting this error when I try to load any CRUD view (besides the Create
form).我将模型的一个属性从
string
更改为CultureInfo
,现在当我尝试加载任何 CRUD 视图(除了Create
表单)时出现此错误。
Error:错误:
One or more validation errors were detected during model generation:
MyProject.Models.CultureInfo: : EntityType 'CultureInfo' has no key defined. Define the key for this EntityType.
MyProject.Models.DateTimeFormatInfo: : EntityType 'DateTimeFormatInfo' has no key defined. Define the key for this EntityType.
CultureInfoes: EntityType: EntitySet 'CultureInfoes' is based on type 'CultureInfo' that has no keys defined.
DateTimeFormatInfoes: EntityType: EntitySet 'DateTimeFormatInfoes' is based on type 'DateTimeFormatInfo' that has no keys defined.
Model:模型:
namespace MyProject.Models
{
public class Project
{
public Project()
{
Sites = new List<Site>();
}
[Key]
public int Id { get; set; }
[Required]
[DisplayName("Name")]
public string Name { get; set; }
[Required]
[DisplayName("Culture")]
[UIHint("ProjectCulture")]
public CultureInfo Culture { get; set; }
// (...)
}
}
In Application_Start()
:在
Application_Start()
:
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ProjectDbContext>());
Looking at similar issues with the same error, I have not found a solution that worked for me.查看具有相同错误的类似问题,我还没有找到适合我的解决方案。 I assume there is a problem mapping
CultureInfo
with the Entity Framework, because the issue only appeared after I changed the type of this attribute, but how can I solve this error without changing it back?我认为将
CultureInfo
与实体框架映射存在问题,因为该问题仅在我更改此属性的类型后才出现,但是如何在不更改它的情况下解决此错误?
by defining通过定义
public virtual CultureInfo Culture { get; set; }
you are indicating EF that you have a related table named CultureInfos: EF convention for public virtual propertes is that that property is a navigation property.您正在指示 EF 您有一个名为 CultureInfos 的相关表:公共虚拟属性的EF 约定是该属性是导航属性。
You should continue to storing CultureInfo.Name as a string and then provide a getter property to retrieve the correponding CultureInfo object.您应该继续将 CultureInfo.Name 存储为字符串,然后提供一个 getter 属性来检索相应的 CultureInfo 对象。
public string CultureName {get; set; }
public CultureInfo Culture {
get { return new CultureInfo(CultureName); }
}
Define [Key]
before defining the property for the primary key, eg在定义主键的属性之前定义
[Key]
,例如
[Key]
public int UserID { get; set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.