This exception message doesn't mean it requires a primary key to be defined in your database, it means it requires a primary key to be defined in your class.
Although you've attempted to do so:
private Guid _id; [Key] public Guid ID { get { return _id; } }
This has no effect, as Entity Framework ignores read-only properties. It has to: when it retrieves a Fruits
record from the database, it constructs a Fruit
object, and then calls the property setters for each mapped property. That's never going to work for read-only properties.
You need Entity Framework to be able to set the value of ID
. This means the property needs to have a setter.
I came here with similar error:
System.InvalidOperationException: 'The entity type 'MyType' requires a primary key to be defined.'
After reading answer by hvd, realized I had simply forgotten to make my key property 'public'. This..
namespace MyApp.Models.Schedule
{
public class MyType
{
[Key]
int Id { get; set; }
// ...
Should be this..
namespace MyApp.Models.Schedule
{
public class MyType
{
[Key]
public int Id { get; set; } // must be public!
// ...
I found a bit different cause of the error. It seems like SQLite wants to use correct primary key class property name. So...
Wrong PK name
public class Client
{
public int SomeFieldName { get; set; } // It is the ID
...
}
Correct PK name
public class Client
{
public int Id { get; set; } // It is the ID
...
}
public class Client
{
public int ClientId { get; set; } // It is the ID
...
}
It still posible to use wrong PK name but we have to use [Key] attribute like
public class Client
{
[Key]
public int SomeFieldName { get; set; } // It is the ID
...
}
This worked for me:
using System.ComponentModel.DataAnnotations;
[Key]
public int ID { get; set; }
Make sure you have the following condition:
[key]
if your primary key name is not Id
or ID
. public
keyword. Example:
public class MyEntity {
[key]
public Guid Id {get; set;}
}
Your Id property needs to have a setter. However the setter can be private.
The [Key]
attribute is not necessary if the property is named "Id" as it will find it through the naming convention where it looks for a key with the name "Id".
public Guid Id { get; } // Will not work
public Guid Id { get; set; } // Will work
public Guid Id { get; private set; } // Will also work
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With