模型验证错误:EntityType没有定义键。定义此EntityType的键

时间:2016-01-21 15:54:11

标签: c# asp.net-mvc entity-framework asp.net-mvc-5 entity-framework-6

我将模型的属性从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与实体框架映射存在问题,因为问题仅在我更改了此属性的类型后出现,但是如何在不更改它的情况下解决此错误?

2 个答案:

答案 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; }