My Shop and Product entities have a one to many relationship, please see my models
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public string Tag { get; set; }
public string Brand { get; set; }
public string Place { get; set; }
public int ShopID { get; set; }
public Shop Shop { get; set; }
}
public class Shop
{
public int ID { get; set; }
public string Name { get; set; }
public string Comment { get; set; }
public string Number { get; set; }
public ICollection<Product> Products { get; set; }
}
public class ShopContext : DbContext
{
public ShopContext(DbContextOptions<ShopContext> options) : base(options)
{
}
public DbSet<Shop> Shops { get; set; }
public DbSet<Product> Products { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Shop>().ToTable("shop");
modelBuilder.Entity<Product>().ToTable("product");
}
}
public class CreateModel : PageModel
{
private readonly ShopContext _context;
public CreateModel(ShopContext context)
{
_context = context;
}
public IActionResult OnGet()
{
ViewData["Shop"] = new SelectList(_context.Shops, "ID", "Name");
return Page();
}
[BindProperty]
public Product Product { get; set; }
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_context.Products.Add(Product);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
}
The shop in create page is a dropdown list, when I post the new product to the handler, I can see the product.ShopID is an ID which exist in Shop table, and the product.Shop.ID as same as the product.ShopID. But when I call saveChangesAsync(), it throws an exception:
MySqlException: Cannot add or update a child row: a foreign key constraint fails (shopdb
.product
, CONSTRAINT FK_product_shop_ShopID
FOREIGN KEY (ShopID
) REFERENCES shop
(ID
) ON DELETE CASCADE)
I tried to set product.Shop to null before call saveChangesAsync method, but still doesn't work, anyone can help?
ASP.NET Core 2.0 Razor Pages Application, Nuget: Pomelo.EntityFrameworkCore.MySql v2.0.1