Tables
Product
-Id (PK)
-Name
ProductExtension
-ProductId (PK)
-Notes
Assign and insert record
Product product = new Product();
product.Name = "Phone";
ProductExtension = productExtension = new ProductExtension();
productExtension.ProductId = product.Id;
productExtension.Notes = "some notes";
//Add and save
context.Products.Add(product);
context.ProductExtensions.Add(productExtension);
context.SaveChangesAsync();
Error:
PostgresException: 23503: Insert or update on table "product_extension" violates foreign key constraint "FK_product_extension_product_product_id"
So product is not created first and product id assigned to productextesion.productid?
Do I need to do an Add
and SaveChanges
for each table? :(
Use navigation property or save before, so EF Core can populate the primary keys (happens only after the entity is saved).
public class ProductExtension
{
public int ProductId { get; set; }
public Product Product { get; set; }
public string Notes { get; set; }
}
Now you can use
Product product = new Product();
product.Name = "Phone";
ProductExtension = productExtension = new ProductExtension();
// assign the whole model to the navigation property
productExtension.Product = product;
productExtension.Notes = "some notes";
// no need for this anymore
// context.Products.Add(product);
//Add and save
context.ProductExtensions.Add(productExtension);
context.SaveChangesAsync();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With