Foreign key exception while adding new entity in entity framework RRS feed

  • Question

  • Hi,

    I am working in winform application which interacts with MySQL database using C# and Entity framework4.0 [VS 2010]. I have two tables Say Table1 and Table2 [Both tables are having primary key as auto incremented number]. These table are having foreign key constraints. Table1 is principle table while Table2 is dependent table. Data from these tables are shown in UltraGrid. Data is being shown in parent child relationship i.e. One row of Table1 is having children rows from Table2. User can add new rows in ultragrid which will make an entry in Table1 and Table2. When i add a row for Table1 and inside this row add one row for Table2 then on saving using context.SaveChanges() method, an exception occurs says "cannot add data because no foreign key is present". I can understand this as first data of Table1 should be saved then from that data primary key will be assigned for Table2 data then one Table2 data can be saved. But in dialog user can first add parent row then add child row and then save the data. I think i am missing something which should be taken care while adding entities which are having foreign key constraints in entity framework. Please help me. Any help will be appreciable. 

    Thanks in advance.

    • Moved by CoolDadTx Tuesday, September 20, 2011 1:22 PM EF related (From:Visual C# General)
    Monday, September 19, 2011 11:46 AM


  • Hi,

    I think it works, you should set the relationship between the Table1 and Table2, for example:

    Talble1.Table2s.add(new Table2());----->Context.Table1s.Add(Tables)----> Call Context.SaveChanges()

    Have a nice day.

    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by ITChamp Tuesday, September 20, 2011 3:54 PM
    Tuesday, September 20, 2011 11:55 AM

All replies