Get the auto-generated ID without inserting and selecting? RRS feed

  • Question

  • Hi,

    I am using Entity Framework in my WPF app.

    I have two entities which are relevant here: Transaction and TransactionItem.

    TransactionItem has a FK to the Id column of Transaction. Which means every TransactionItem has to be connected to a Transaction via it's ID.

    When a transaction including some items is completed, I want to create a new Transaction object. Then I would like to create all the TransactionItem objects with it's ID and insert them as well. Only problem is, I can't know it's ID before I write it to the DB.

    Is there a more elegant way for this problem rather then insert -> commit -> select?


    Tuesday, February 9, 2016 5:44 PM


  • It´s not necessary to set ID implicit, you can add TransactionItem to Transaction collection: transaction.TransactioItem.add(transactionitem), and when you commit it then ID is set to all related entities.

    After commit, you dont need select again, automatically you get ID's. All of this when you configure ID as identity.

    • Edited by JCourech Tuesday, February 9, 2016 7:13 PM
    • Marked as answer by Tomer Agmon Wednesday, February 10, 2016 6:28 AM
    Tuesday, February 9, 2016 7:11 PM