Cannot add or update a child row: a foreign key constraint fails in vb.net

894 Views Asked by At

I have an error on create or add product in mysql is there something wrong. is there something wrong with my code? thanks

CATEGORY PRODUCTS MySqlException was unhandled

Public Interface ISearchable Property Id() As Integer Property Name() As String End Interface

An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in ServiceStack.OrmLite.dll

Additional information: Cannot add or update a child row: a foreign key constraint fails (`inventory_manager`.`products`, CONSTRAINT `FK_products_categories_CategoryId` FOREIGN KEY (`CategoryId`) REFERENCES `categories` (`Id`) ON DELETE CASCADE)
'update code for table  products
    <[Alias]("products")>
    Public Class Product
        Implements ISearchable

        <PrimaryKey, AutoIncrement>
        Public Property Id() As Integer Implements ISearchable.Id
        <ForeignKey(GetType(Category), OnDelete := "CASCADE")>
        Public Property CategoryId() As Integer
        Public Function GetCategory() As Category
            Return Db.Get().SingleById(Of Category)(Me.CategoryId)
        End Function

    End Class
'update code for table categories
<[Alias]("categories")>
Public Class Category
        Implements ISearchable

        <PrimaryKey, AutoIncrement>
        Public Property Id() As Integer Implements ISearchable.Id
        Public Property Name As String = String.Empty Implements ISearchable.Name
    End Class

1

There are 1 best solutions below

1
Ananth MK On

It looks like the first table is category table with id as Primary key and the second table is products with categoryid as foreign key. While adding/editing records in products table, make sure the categoryid value is present in the parent table's id column. This is what the error means.