5
votes

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? :(

1
You didn't even set the Id in your example, how do you expect it to use an ID for the relationship? The ID is only generated once the model is saved. Either you have to save before assigning it or use navigation properties - Tseng

1 Answers

2
votes

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();