Entity Framework Core, error Postgres violates foreign key constraint

asp.net-core c# database entity-framework-core postgresql

Question

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
1
10/25/2018 7:55:18 AM

Accepted Answer

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();
1
4/12/2017 6:06:26 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow