none
INSERT statement conflicted with the FOREIGN KEY RRS feed

  • Question

  • /*Post Product*/
    var category = await _context.ProductCategories.ToListAsync();

    if (category == null)
    {
    var addcategory = new ProductCategory
    {
    Id = model.ProductCategoryId,
    Name = "Lotion"
    };

    var product = new Product
    {
    Barcode = model.Barcode,
    ProductName = model.ProductName,
    ProductType = model.ProductType,
    Features = model.Features,
    Price = model.Price,
    ImageUrl = model.ImageUrl,
    Quantity = model.Quantity,
    Usage = model.Usage,
    Description = model.Description,
    BillingAddress = model.BillingAddress,
    OutOfStock = model.OutOfStock,
    ProductCategoryId = model.ProductCategoryId,
    ProductCategory = addcategory,
    SellerId = model.SellerId,
    SellerName = model.SellerName,
    TC = model.TC
    };

    try
    {
    await _context.Products.AddAsync(product);
    await _context.SaveChangesAsync();
    return Ok(new JsonResult("The Product was Added Successfully"));
    }
    catch (Exception ex)
    {
    throw ex;
    }
    }
    • Moved by CoolDadTx Thursday, December 5, 2019 3:02 PM EF related
    Wednesday, December 4, 2019 8:43 AM

All replies

  • What is your question?

    Based on title you get error because inserting foreign key reference that is somehow invalid. Maybe referencing to value that is not in database. Could be for example model.SellerId, but its hard to know without more details.

    Wednesday, December 4, 2019 9:22 AM
  • It's a pity that you have added so little detail to your question. My guess is that the problem may be in the "addcategory" part. You select the category from the ProductCategory table, and if it doesn't exist then you "new" a category. And then you assign this new category to the Product and try to save the product. If there is a foreign key linking the Product table to the ProductCategory table, then you get an error because the category that you are assigning to the product does not exist in the database. No, doing a "new" for the category does not create it in the database, it is only created in memory but it is not saved automatically. To save it, you would need to Add it to the _context.ProductCategories and then SaveChanges().
    Wednesday, December 4, 2019 10:31 AM
  • Hello,

    Sounds like a foreign key constraint violation. In short, the foreign key cannot have a value in that column that is not also in the primary key column of the referenced table.

    So you are trying to insert a record with a value in the foreign key column that doesn't exist in the foreign table.

    Not knowing your data my best guess is one of the following are in violation of a FK constraint as per above.

    ProductCategoryId = model.ProductCategoryId

    SellerId = model.SellerId


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Wednesday, December 4, 2019 10:44 AM
  • Hi Nhlahla Mike,
    As Kareninstructor said, there is no foreign key value that inserted in your reference table.
    So an error occurs when you insert a value into the foreign key column. 
    To handle this issue, you can insert null into foreign key column or insert the foreign key into the reference table first.
    Here are some similar issues you can refer to.
    [The INSERT statement conflicted with the FOREIGN KEY constraint. The conflict occurred in database]
    [INSERT statement conflicted with the FOREIGN KEY constraint. The statement has been terminated]
    Best Regards,
    Daniel Zhang
    Note: This response contains a reference to a third party World Wide Web site. Microsoft is providing this information as a convenience to you. Microsoft does not control these sites and has not tested any software or information found on these sites; Therefore, Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. There are inherent dangers in the use of any software found on the Internet, and Microsoft cautions you to make sure that you completely understand the risk before retrieving any software from the Internet.

    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, December 5, 2019 2:04 AM
  • I understood that, but I wanted to insert smultanously which is not working. Looks like I can't insert to foreign key table and save the same time in the same method
    Thursday, December 5, 2019 2:30 PM
  • Absolute, but it refuses to use save changes twice in the same method. 

    It only update the product categories but the Product table is not updated

    Thursday, December 5, 2019 2:49 PM
  • Absolute, but it refuses to use save changes twice in the same method. 

    It only update the product categories but the Product table is not updated

    Peek into changes with the following NuGet package and GitHub repo. Check the state of new data in the Product table via the State property of the new row.

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Thursday, December 5, 2019 2:55 PM
  • Absolute, but it refuses to use save changes twice in the same method. 

    It only update the product categories but the Product table is not updated

    I do not understand what you are trying to do. I only see one SaveChanges().
    Thursday, December 5, 2019 3:58 PM