Error: the entity type requires a primary key

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

    Yet another reason may be that your entity class has several properties named somhow /.*id/i - so ending with ID case insensitive AND elementary type AND there is no [Key] attribute.

    EF will namely try to figure out the PK by itself by looking for elementary typed properties ending in ID.

    See my case:

    public class MyTest, IMustHaveTenant
    {
      public long Id { get; set; }
      public int TenantId { get; set; }
      [MaxLength(32)]
      public virtual string Signum{ get; set; }
      public virtual string ID { get; set; }
      public virtual string ID_Other { get; set; }
    }
    

    don't ask - lecacy code. The Id was even inherited, so I could not use [Key] (just simplifying the code here)

    But here EF is totally confused.

    What helped was using modelbuilder this in DBContext class.

                modelBuilder.Entity(f =>
                {
                    f.HasKey(e => e.Id);
                    f.HasIndex(e => new { e.TenantId });
                    f.HasIndex(e => new { e.TenantId, e.ID_Other });
                });
    

    the index on PK is implicit.

提交回复
热议问题