Error: the entity type requires a primary key

后端 未结 11 1659
走了就别回头了
走了就别回头了 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:57

    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.

提交回复
热议问题