The INSERT statement conflicted with the FOREIGN KEY constraint "FK_..."

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Good Guy
    New Member
    • Nov 2010
    • 2

    #1

    The INSERT statement conflicted with the FOREIGN KEY constraint "FK_..."

    The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Customers_C ontact".
    The conflict occurred in database "BreakAway" , table "dbo.Contac t", column 'ContactID'.
    The statement has been terminated.

    Hi, all. This is my maiden post.
    Some background:
    I am doing a C# project using Entity Framework 4.0 in Visual Studio 2010 and SQL Server 2005 Expresss.
    The project is from the book, Programming Entity Framework, Chapter 9, which uses an edmx model built on the BreakAway database.

    The project uses <object> datasources to bind data, and the little code that is added is create and attach the related Contact record when a new Customer record is passed to the context. The context is updating edits fine, but an insert for a new <Customer> record throws this error:

    The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Customers_C ontact". The conflict occurred in database "BreakAway" , table "dbo.Contac t", column 'ContactID'.
    The statement has been terminated.

    <Contact> entity has a 1-0..1 relationship with <Customer> entity.
    Contact.Contact ID is both an EntityKey and Identity, while Customer.Contac tID is an EntityKey and a Foreign Key.

    EF is supposed to manage identity keys, primary and foreign keys, so if my edmx and database are both set up correctly, why am I getting this error?

    And how can I check the contents of the context just before it calls SaveChanges?
  • Bryan Cheung
    New Member
    • Nov 2010
    • 55

    #2
    Hi Good guy,

    The error is telling you that you first have to add a contact row so you have a ContactID and afterwards you can insert a Customer with the ContactID. Unless you are using a existing ContactID. This has to do with relationships between tables and I believe your Customer.Contac tID is set to "not null" so it requires a (existing)Conta ctID.

    You just have to or set CustomerID.Cont actID to nullable(if not every customer has a contact) or use a existing contactid, so insert contact row before customer row or switch relation to Contact -> Customer which means a Contact.Custome rID field and remove the Customer.Contac tID field. Depends on your requirements which choice you make.

    Good luck,
    B.

    Comment

    • Good Guy
      New Member
      • Nov 2010
      • 2

      #3
      Thanks, Bryan, for the info. I went over the code and found the cause of my bug - a small typo in my code!

      Comment

      Working...