I'm currently learning RESTful API with ASP.NET Core. I have an existing SQL Server database, with a table feedback that includes an IDENTITY(1,1) PRIMARY KEY id column.
I have the model setup as:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics.CodeAnalysis;
namespace Feedback_RESTful_API.Models
{
public class Feedback
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
}
Data as:
using Feedback_RESTful_API.Models;
using Microsoft.EntityFrameworkCore;
namespace Feedback_RESTful_API.Data
{
public class ApiContext : DbContext
{
public DbSet<Feedback> Feedbacks { get; set; }
public ApiContext(DbContextOptions<ApiContext> options) : base(options)
{
}
}
}
And controller as:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Feedback_RESTful_API.Models;
using Feedback_RESTful_API.Data;
namespace Feedback_RESTful_API.Controllers
{
[Route("[controller]")]
[ApiController]
public class FeedbackController : ControllerBase
{
private readonly ApiContext _context;
public FeedbackController(ApiContext context)
{
_context = context;
}
[HttpPost]
public JsonResult Create(Feedback feedback)
{
//Add the new entry
_context.Feedbacks.Add(feedback);
//Save the db
_context.SaveChanges();
//Return response
return new JsonResult(Ok(feedback));
}
}
}
But when I run the app and test the POST call through Swagger UI, I get the error:
System.InvalidOperationException: The entity type 'Feedback' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'. For more information on keyless entity types, see https://go.microsoft.com/fwlink/?linkid=2141943.
I can't seem to find any solutions since most search results are in regards to inserting into the identity column, which I don't need since I just want the database server to handle it, or setting up the database/table from scratch through Entity Framework Core, which I didn't do since the database already existed in SQL Server.
public. Typically I define them aspublic int Id { get; protected set; }to discourage misusing the setter.