實體框架核心,錯誤Postgres違反了外鍵約束

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

Product
-Id (PK)
-Name

ProductExtension
-ProductId (PK)
-Notes

分配和插入記錄

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

錯誤

PostgresException:23503:在表“product_extension”上插入或更新違反外鍵約束“FK_product_extension_product_product_id”

因此,不首先創建產品,將產品ID分配給productextesion.productid?我是否需要為每個表執行AddSaveChanges ? :(

一般承認的答案

使用導航屬性或保存之前,因此EF Core可以填充主鍵(僅在保存實體後才會發生)。

public class ProductExtension
{
    public int ProductId { get; set; }
    public Product Product { get; set; }
    public string Notes { get; set; }
}

現在你可以使用了

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


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow