none
Insert with a Foreign Key Value

    Question

  • I have 2 tables [A and B]

    Columns in Table A:

    1. APkId - Primary Key of A [Identity Column]
    2. BFkId - Foreign Key of B[Field BPkId], Nullable
    3. OtherColumnsinA
    Columns in Table B:
    1. BPkId - Primary Key of B [Identity Column]
    2. AFkId - Foreign Key of A[Field APkId], Not Null
    3. OtherColumnsinB

    And the LINQ code, i use is as follows:
    A objA = new A();
    A.OtherColumnsinA= "Values";

    B objB = new B();
    B.OtherColumnsinB = "Values";
    A.B.Add(objB);

    db.A.InsertonSubmit(objA);
    db.SubmitChanges();

    Answer:
    The Table B gets filled with the proper data in all columns including the Foreign Key column of A. But the A table is not populated with the Foreign Key Column of A.

    Please let me know What should i do to get the Foreign Key column populated in table A as well.

    Thanks for the help.

    Regards,
    Vimalkumar


     

     

    Monday, July 26, 2010 7:25 AM

Answers

  • I would say that your database design is not good; so it should be changed. I cannot see a good reason to have both tables holding each other's primary key as a foreign key.

    If, however, you are tied to this design then you can make a second step after the SubmitChanges(). The objects' primary key values are set by the SubmitChanges, so you can do the following

    A.BFkId = B.BPkId;
    db.SubmitChanges();

    Monday, July 26, 2010 4:37 PM

All replies

  • I would say that your database design is not good; so it should be changed. I cannot see a good reason to have both tables holding each other's primary key as a foreign key.

    If, however, you are tied to this design then you can make a second step after the SubmitChanges(). The objects' primary key values are set by the SubmitChanges, so you can do the following

    A.BFkId = B.BPkId;
    db.SubmitChanges();

    Monday, July 26, 2010 4:37 PM
  • Hi Vimalkumar,

    I agree with John. I suggest you reconsider the needs of designing the database like that.  You may get into a cycle when you set changes to this two kinds of entities. If you still want to keep the design, then you can refer to John's suggestion to set the foreign key column of A after the SubmitChanges().

    Best regards,
    Alex Liang

     


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Wednesday, July 28, 2010 9:56 AM