Search code examples
c#sqlormmassive

Want to use identity returned from insert in subsequent insert in a transaction


I'm using Rob Conery's Massive for database access. I want to wrap a transaction around a couple of inserts but the second insert uses the identity returned from the first insert. It's not obvious to me how to do this in a transaction. Some assistance would be appreciated.

var commandList = new List<DbCommand>
    {
        contactTbl.CreateInsertCommand(new
            {
                newContact.Name,
                newContact.Contact,
                newContact.Phone,
                newContact.ForceChargeThreshold,
                newContact.MeterReadingMethodId,
                LastModifiedBy = userId,
                LastModifiedDate = modifiedDate,
            }),
        branchContactTbl.CreateInsertCommand(new
            {
                newContact.BranchId,
                ContactId = ????, <-- how to set Id as identity from previous command
            }),
    };

Solution

  • Can you just do it in a stored proc? The you can use scope_identity or better yet the output clause to get the value(s) you need. And all the inserts to all the tables are in one transaction which can be rolled back if any of them fail.