Entity Framework One or more validation error were detected Exception
Exception: One or more validation errors were detected during model generation. EntityType has no key defined. Define the key for this EntityType.
StackOverflow Related Questions
- EntityType has no key defined error
- mvc entity type has no key defined
- Entity type has no key defined EF6
Answer
There are several reasons this can happen and you can fix it very easily when this message occurs.
Scenario 1:
You've forgotten to include a key.
public class Customer { public string Name { get; set; } public List<Invoice> Invoices { get; set; } }
All EF models need a key, so make sure that your model class contains key.
public class Customer { public int CustomerID { get; set; } public string Name { get; set; } public List<Invoice> Invoices { get; set; } }
Scenario 2:
Primary key member does not have getter/setter.
public class Customer { public int CustomerID; // other properties }
It needs to be a property but not a field.
public class Customer { public int CustomerID { get; set; } // other properties }
Scenario 3:
The Id member is not public.
public class Customer { protected int CustomerID { get; set; } // other properties }
All your Id members must be public.
public class Customer { public int CustomerID { get; set; } // other properties }
Scenario 4:
Class name is not equal to Id member name.
public class Customer { public int CustId { get; set; } public string Name { get; set; } public List<Invoice> Invoices { get; set; } }
Code First infers that a property is a primary key if a property on a class is named Id
(not case sensitive), or the class name followed by Id
. If the type of the primary key property is numeric or GUID it will be configured as an identity column.
Make sure that primary key property is either named Id
or CustomerId
in your models.
public class Customer { public int CustomerID { get; set; } public string Name { get; set; } public List<Invoice> Invoices { get; set; } }
Or add [Key]
to give EF a hint that it is the identity property and don't forget to add using System.ComponentModel.DataAnnotations;
public class Customer { [Key] public int CustId { get; set; } public string Name { get; set; } public List<Invoice> Invoices { get; set; } }
ZZZ Projects