Search code examples
c#.net-coreaspnetboilerplate

Returning last inserted id in C# using Repository


In a .NET Core/C# application, using the Boilerplate framework I use repositories for data access:

await _licenseRepository.InsertAsync(license);

But in a method I need to do two inserts in two different tables, and then do the relationship:

public async Task Insert(License license, LicenseRenewal licenseRenewal)
{
    var l = await _licenseRepository.InsertAsync(license);
    var lr = await _licenseRenewalRepository.InsertAsync(licenseRenewal);
    await AssignRenewal(l.Id, lr.Id);
}

The problem is that when I do the Insert I do not get the IDs of the new data and so it fails to do the AssignRenewal.

How do I get the ID of the inserted data?


Solution

  • aspnetboilerplate.com/Pages/Documents/Repositories#insert states:

    "[...] The InsertAndGetId method returns the Id of a newly inserted entity.[...]"

    So you should try

    Task<TPrimaryKey> InsertAndGetIdAsync(TEntity entity);