5

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 Commented Apr 12, 2017 at 6:02

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

2 Comments

this will first create the product and then create a phone extension?
Yes, because EF Core will see that the assigned Product doesn't exist yet. If you have loaded the Product previously (and hence it has an id) then Product won't be created again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.