Entity type has no key defined EF6

2019-04-29 20:21发布

问题:

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:

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



回答2:

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