Get ID of newly created record

Topics: Writing modules
Nov 10, 2011 at 7:04 PM

When using normal SQL commands, it's possible to get the ID of a record that was just inserted using scope_identity. Is there an equivalent when using IRepository?

My service file has the following (this is not a ContentPart):

_unitRepository.Create(new UnitRecord
{
    UnitType = ...,
    UnitNumber = ...
    ...
});

I then need to pass the ID of the new UnitRecord to another method to create a record in a different table. I suppose I could just sort the table descending by the ID and select the first record, but I'd be more comfortable specifically passing the new ID.

Thanks!

Nov 10, 2011 at 7:13 PM

Yes:

var record = new UnitRecord
{
    UnitType = ...,
    UnitNumber = ...
    ...
};
_unitRepository.Create(record);
return record.Id;

Nov 10, 2011 at 7:17 PM

Ahhh...perfect. So just create a UnitRecord object outside the Create method and after the Create method runs, the UnitRecord object will pick up the new Id. Thanks!