I am building a React web app using .NET Core api and Entity Framework connected to Azure database. The issue is when I try to add a new item through the api's http, I get this error:
SqlException: Cannot insert explicit value for identity column in table 'Products' when IDENTITY_INSERT is set to OFF.
Most of the solutions I found were to add .ValueGeneratedOnAdd()
in the context's file to the id column or add this line of code in my Model (above the ID)
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id { get; set; }
However, none of the solutions worked. Any advices would be appreciated as currently I have no clue how to change that settings without using sql.
Here is also my HttpPost method:
[HttpPost]
[Route("CreateProduct")]
public void AddProduct(Product p)
{
ProductHandler _handler = new ProductHandler();
_handler.CreateProduct(p);
}
and the handler:
public List<Product> GetProducts()
{
ApplicationDbContext context;
using (context = new ApplicationDbContext())
{
var listOfProducts = context.Products;
products.Clear();
foreach (Product product in listOfProducts)
{
products.Add(product);
}
context.Dispose();
}
return products;
}
public void CreateProduct(Product p)
{
using (ApplicationDbContext context = new ApplicationDbContext())
{
context.Products.Add(p);
context.SaveChanges();
}
}
The issue arises when you pass an ID to the backend server, which should not be done. Entity Framework is configured to automatically generate a unique ID for each entity by using the [DatabaseGenerated(DatabaseGeneratedOption.Identity)] attribute. Therefore, you need to ensure that the ID remains at its default value, typically 0, when adding a new entity to the database, allowing EF Core to correctly handle and generate a unique ID for it.
You could create web api app and use test code as follow
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private readonly ApplicationDbContext _context;
public ProductsController(ApplicationDbContext context)
{
_context = context;
}
[HttpPost]
public async Task<ActionResult<Product>> AddProduct(Product product)
{
_context.Products.Add(product);
await _context.SaveChangesAsync();
return CreatedAtAction("GetProduct", new { id = product.Id }, product);
}
[HttpGet("{id}")]
public async Task<ActionResult<Product>> GetProduct(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
return product;
}
}