I'm developing an ASP.NET Core application and encountering an issue with Entity Framework Core. Despite having defined a primary key in my Task entity, I get an error when trying to create an instance of DbContext.
The error message is:
Unable to create a 'DbContext' of type ''. The exception 'The entity type 'Task' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'.
Here is the relevant code for my Task entity:
using System.ComponentModel.DataAnnotations;
namespace taskManager.Services.TaskApi.Models
{
public class Task
{
[Key]
public int TaskId { get; set; }
[Required]
public string Title { get; set; }
public string Description { get; set; }
[Required]
public DateTime DateTime { get; set; }
public bool IsCompleted { get; set; }
public bool IsImportant { get; set; }
}
}
And my AppDbContext looks like this:
using Microsoft.EntityFrameworkCore;
using taskManager.Services.TaskApi.Models;
namespace taskManager.Services.TaskApi.Data
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
public DbSet<Task> Tasks { get; set; }
}
}
The DbContext is registered in my Program.cs as follows:
var builder = WebApplication.CreateBuilder(args);
// ... other configurations ...
builder.Services.AddDbContext<AppDbContext>(option =>
{
option.UseSqlServer("Server=DESKTOP-39TI737\\SQLEXPRESS;Database=Manage_Task;Trusted_Connection=True;TrustServerCertificate=True");
});
// ... other configurations ...
Taskexists in the framework already, perhaps you are referencing the wrong one. In the long run, it's probably better to rename it anyway.