簡體   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