Error: the entity type requires a primary key

后端 未结 11 1525
走了就别回头了
走了就别回头了 2020-12-02 15:30

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

相关标签:
11条回答
  • 2020-12-02 15:39

    This worked for me:

    using System.ComponentModel.DataAnnotations;
    
    [Key]
    public int ID { get; set; }
    
    0 讨论(0)
  • 2020-12-02 15:46

    Removed and added back in the table using Scaffold-DbContext and the error went away

    0 讨论(0)
  • 2020-12-02 15:47

    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.

    0 讨论(0)
  • 2020-12-02 15:48

    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
       ...
    }
    
    0 讨论(0)
  • 2020-12-02 15:48

    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
    
    0 讨论(0)
  • 2020-12-02 15:53

    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.

    0 讨论(0)
提交回复
热议问题