Object type does not have an EF6 definable key

Here is my code, although I have already clarified the key attribute, but there is still 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 am getting is:

The Contact entity type does not have a key. Define a key for this entity type.
Object type: EntitySet "Contacts" is based on the type "Contacts", which does not have specific keys

+5
source share
2 answers

If you use EF Code First (not listed in your question), you will need to change the ContactId property name to ContactId in order to negotiate an agreement with ClassName + Id to determine the key for your contact entity type.

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

+7
source

I know that this has already been answered in one way, but I wanted to publish a different approach for those who are faced with this.

This error occurred to me, even when I had a [Key] property defined that I wanted to designate as the primary key. The error that occurred during the Update-Database command was caused by the fact that my migration name (via Add-Migration) matches the name I wanted to add. This is because the Add-Migration team created a partial class that matched the name of the object.

For instance:

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

Doesn't work on execution:

 Add-Migration Contacts Update-Database 

because the signature of the migration class looked like below, and the body did not contain a property with the [Key] attribute

 public sealed partial class Contacts 

To solve this problem, I removed the migration with the same name and changed the Add-Migration command:

 Add-Migration ContactsTable Update-Database 
0
source

Source: https://habr.com/ru/post/1207943/


All Articles