none
Attach foreign key to entity object RRS feed

  • Question

  • I've this form. I want to insert to two tables simultaneously.

    1st table:

    - user_id

    - user_name


    2nd table:

    - partner_id

    - partner_name

    - partner_to_user_fk


    The partnerName inserting is ok and after a get partnerId. I want to attach partnerId to partner_contact inserting. I tried this but didn't work. What is the standard solution for this case?

    private void button1_Click(object sender, EventArgs e) { partners pa = new partners(); pa.partnerName = partnerNameTextBox.Text.ToString(); id = pa.partnerId;

      if (id != null)
      {
        partner_contacts pc = new partner_contacts { partner_FK = id };
        valinor.partner_contacts.AddObject(pc);
        valinor.AttachTo("partner_contacts", pc);            
    valinor.SaveChanges();
    } }



    Wednesday, September 26, 2012 9:16 AM

Answers

  • Hi Akoss,

    Welcome to the MSDN forum.

    Based on the code you provided, the pa has not been tracked by object context. Since if you create a new entity object without explicitly assigning the primary key value, the object will be initialized with a primary key value: 0. After the object is tracked by object context, if you call SaveChanges, the value will be updated (if you set primary key as an identity column). In your code, pa has not been tracked, so if SaveChanges are called, the partner_FK of pc is 0, which will cause the inset error. You can check following code snippet:

      partners pa = new partners();
      pa.partnerName = partnerNameTextBox.Text.ToString();
      valinor.Partners.AddObject(pa);
    
      partner_contacts pc = new partner_contacts { partner_FK = pa.partnerId };
      valinor.partner_contacts.AddObject(pc);
      valinor.SaveChanges();

    Good day.


    Alexander Sun [MSFT]
    MSDN Community Support | Feedback to us

    • Marked as answer by Alexander Sun Tuesday, October 9, 2012 9:01 AM
    Thursday, September 27, 2012 6:23 AM