繁体   English   中英

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

[英]Model validation error: EntityType has no key defined. Define the key for this EntityType

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

通过定义

public virtual CultureInfo Culture { get; set; }

您正在指示 EF 您有一个名为 CultureInfos 的相关表:公共虚拟属性的EF 约定是该属性是导航属性。

您应该继续将 CultureInfo.Name 存储为字符串,然后提供一个 getter 属性来检索相应的 CultureInfo 对象。

public string CultureName {get; set; }
public CultureInfo Culture {
    get { return new CultureInfo(CultureName); }
}

在定义主键的属性之前定义[Key] ,例如

[Key]
public int UserID { get; set; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM