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

asp.net-mvc asp.net-mvc-5 c# entity-framework entity-framework-6

Question

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).

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():

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?

1
0
1/21/2016 4:25:04 PM

Popular Answer

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.

You should continue to storing CultureInfo.Name as a string and then provide a getter property to retrieve the correponding CultureInfo object.

public string CultureName {get; set; }
public CultureInfo Culture {
    get { return new CultureInfo(CultureName); }
}
1
1/21/2016 4:08:43 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow