Search code examples
entity-frameworkasp.net-mvc-5models

Entity type has no key defined EF6


Here is my code although I already have refined the key attribute but still there is a problem.

public class Contacts
{
    [Key]
    public int ContactId { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
}

The error I get is:

Entity Type 'Contacts' has no key defined. Define the key for this entity type.
Entity type: EntitySet 'Contacts' is based on type 'Contacts' that has no key defined


Solution

  • If you are using EF Code First (not specified in your question), you will need to change the ContactId property name to ContactsId to match the convention of ClassName + Id in order to define the key for your Contacts entity type.

    See the MSDN Code First Conventions: http://msdn.microsoft.com/en-us/data/jj679962.aspx