Entity type has no key defined EF6

asp.net-mvc-5 entity-framework models

Question

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

1
5
8/26/2015 3:33:42 PM

Accepted Answer

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

7
11/29/2014 9:59:09 PM

Popular Answer

I know that this has already been answered in one fashion, but I wanted to post a different approach for those who encounter this.

This error occurred for me even while having [Key] defined above the property I wanted to designate as the Primary Key. The error, occurring during the Update-Database command, was caused by my naming of the migration (through Add-Migration) the same as the entity that I wanted to be added. This is because the Add-Migration command created a partial class which matched the entity name.

For example:

public class Contacts
{
    [Key]
    public int ContactId { get; set; }
    public string Name { get; set; }
}

Didn't work when I executed:

Add-Migration Contacts
Update-Database

because the migration class signature looked like the below, and the body contained no property with the [Key] attribute

public sealed partial class Contacts

To solve this, I deleted the identically-named migration and modified the Add-Migration command:

Add-Migration ContactsTable
Update-Database


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