gpt4 book ai didi

c# - Entity Framework Core,报错Postgres violates foreign key constraint

转载 作者:搜寻专家 更新时间:2023-10-30 23:35:26 24 4
gpt4 key购买 nike

表格

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: Insert or update on table "product_extension" violates foreign key constraint "FK_product_extension_product_product_id"

所以产品没有先创建,产品 ID 分配给 productextesion.productid? 我是否需要为每个产品执行 AddSaveChanges table ? :(

最佳答案

使用导航属性或之前保存,因此 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();

关于c# - Entity Framework Core,报错Postgres violates foreign key constraint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43359631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com