我将模型的属性从string
更改为CultureInfo
,当我尝试加载任何CRUD视图(Create
表单除外)时,我现在收到此错误。
错误:
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.
型号:
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; }
// (...)
}
}
在Application_Start()
:
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ProjectDbContext>());
查看同样错误的类似问题,我还没有找到适合我的解决方案。我假设将CultureInfo
与实体框架映射存在问题,因为问题仅在我更改了此属性的类型后出现,但是如何在不更改它的情况下解决此错误?
答案 0 :(得分:1)
通过定义
public virtual CultureInfo Culture { get; set; }
您指示EF您有一个名为CultureInfos的相关表:公共虚拟财产的EF convention是该属性是导航属性。
您应该继续将CultureInfo.Name存储为字符串,然后提供getter属性以检索相应的CultureInfo对象。
public string CultureName {get; set; }
public CultureInfo Culture {
get { return new CultureInfo(CultureName); }
}
答案 1 :(得分:0)
在定义主键的属性之前定义[Key]
,例如
[Key]
public int UserID { get; set; }