Error indicating a SQL Server table does not have a primary key

I am developing a new version of an existing program, this time interacting with a corporate database.

In my attempt to build a record and add it to a table within the database, I get the following error:

System.InvalidOperationException: 'The entity type 'nonAF1067Fields' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'. For more information on keyless entity types, see Bing'

This error implies that the table does not contain a primary key, although the primary key("ID") can be plainly seen in the SSMS representation of the table.

How do I get my app to recognize the primary key? Any other possibilities as to why the app thinks that the table does not have a key?

I think you didn't define a key in Entity Framework, it is not the database. Make sure your key is public.

If you have a primary key in the database and the EF model does not recognize it, you should add an attribute to the public property in your class. If your primary key is a single column named Id, EF interprets it as PK. Otherwise you need to tell it what the key is. Since you do have a column ID (and it is not case sensitive), I don't know why EF is unable to infer. Nonetheless, I would try explicitly adding the decorator. See here

1 Like