表
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?
我是否需要为每个表执行Add
和SaveChanges
? :(
答案 0 :(得分:1)
使用导航属性或保存之前,因此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();