Search code examples
asp.netentity-frameworkasp.net-coreentity-framework-coreef-fluent-api

KeyAttribute attribute does not work when setting primary key


The Entity Framework Core version is 7.0.10. While getting data from database, it throws out no primary key exception even I have already set it up in model class.

The entity type 'Order' requires a primary key to be defined.

Here is the code.


[Table("xxxTable")]
public class Order
{
    [Key]
    [Column("ID")]
    public int Id;
    public string Name { get; set; }
}

//Here is the method to get data from database
public async Task<Order> GetOrdersByDay(int days)
{
   Order r = await this._dbContext.Orders.FirstOrDefaultAsync();
   return r;
}

I have set primary key in class Order with attribute [Key], but it does not work. The exception is still there.

If I use fluent API to set up the primary key, it is working fine.

modelBuilder.Entity<Order>(entity =>
{
    entity.HasKey(t => t.Id);
});

Why does not [Key] work? How can I resovle it when I only want to use attribute instead of fluent API?


Solution

  • Perhaps try adding { get; set; } for the Id.