I'm unsure how to use EF Core to insert a new entity that has existing children.
I have a list of Products
in the database. I am attempting to create a new order that has a list of existing products.
This is the Product
class:
public class Product
{
public long ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
[Column(TypeName = "decimal(8, 2)")]
public decimal Price { get; set; }
public string Category { get; set; }
}
And this is the Order
class
public class Order
{
public long ID { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
public bool Giftwrap { get; set; }
public IEnumerable<Product> Products { get; set; }
}
When I attempt to insert a new order with existing products:
[HttpPost]
public IActionResult Post([FromBody] Order model)
{
context.Add(model);
context.SaveChanges();
return Ok(model);
}
I get an error:
SqlException: Cannot insert explicit value for identity column in table 'Products' when IDENTITY_INSERT is set to OFF.
This is the DbContext
:
using Microsoft.EntityFrameworkCore;
namespace angularsportsstorenetcore2.Models
{
public class StoreDbContext : DbContext
{
public StoreDbContext(DbContextOptions<StoreDbContext> options)
: base(options) { }
public DbSet<Product> Products { get; set; }
public DbSet<Order> Orders { get; set; }
}
}