I would like to expand the question asked on this thread
Binding listbox to observablecollection
by giving it an ability to persistent the data. The structur
This worked for me:
using System.ComponentModel.DataAnnotations;
[Key]
public int ID { get; set; }
Removed and added back in the table using Scaffold-DbContext and the error went away
None of the answers worked until I removed the HasNoKey() method from the entity. Dont forget to remove this from your data context or the [Key] attribute will not fix anything.
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
...
}
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
When I used the Scaffold-DbContext command, it didn't include the "[key]" annotation in the model files or the "entity.HasKey(..)" entry in the "modelBuilder.Entity" blocks. My solution was to add a line like this in every "modelBuilder.Entity" block in the *Context.cs file:
entity.HasKey(X => x.Id);
I'm not saying this is better, or even the right way. I'm just saying that it worked for me.