Search code examples
postgresqlservicestackormlite-servicestack

How to return the identity value from an insert with ServiceStack OrmLite - PostgreSQL


Nuget: ServiceStack.4.0.25 ServiceStack.OrmLite.4.0.25 ServiceStack.OrmLite.PostgreSQL.4.0.25

Given this Schema

-- ----------------------------
-- Table structure for loan_application
-- ----------------------------
DROP TABLE IF EXISTS "public"."loan_application";
CREATE TABLE "public"."loan_application" (
"row_id" int4 DEFAULT nextval('loan_application_row_id_seq'::regclass) NOT NULL,
"first_name" char(50) COLLATE "default",
"last_name" char(50) COLLATE "default"
)
WITH (OIDS=FALSE)

;

-- ----------------------------
-- Alter Sequences Owned By 
-- ----------------------------

-- ----------------------------
-- Primary Key structure for table loan_application
-- ----------------------------
ALTER TABLE "public"."loan_application" ADD PRIMARY KEY ("row_id");

and these dtos

[Route("/loanapplication", "POST")]
public class LoanApplication
{
    [AutoIncrement]
    public int RowId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class LoanApplicationResponse
{
    public int Id { get; set; }
    public ResponseStatus ResponseStatus { get; set; }
}

used by this service

public class LoanApplicationService : Service
{
    public DataRepository DataRepository { get; set; }

    public object Any(LoanApplication request)
    {
        var id = DataRepository.AddEntry(request);

        return new LoanApplicationResponse { Id = id };
    }
}

public class DataRepository
{
    public IDbConnectionFactory DbConnectionFactory { get; set; }

    public int AddEntry(LoanApplication loanApplication)
    {
        using (var db = DbConnectionFactory.OpenDbConnection())
        {

< UPDATE >

            db.Insert(loanApplication, true); // wrong way

            db.Save(loanApplication);// correct way

            return loanApplication.RowId;
        }
    }
}

I am unable to retrieve the id after insert. I've tried passing true and false as the second param and neither return the id.

Thank you, Stephen


Solution

  • See this previous answer on how to retrieve automatically inserted ids, e.g:

    You can either use db.Save() to automatically populate the AutoIncrement Id, e.g:

    db.Save(loanApplication);
    loanApplication.Id //populated with the auto-incremented id
    

    Otherwise you can select the last insert id using:

    var itemId = db.Insert(loanApplication, selectIdentity:true);
    

    Note: selectIdentity:true just returns the auto-incremented id, it does not modify the loanApplication, this is what db.Save() does.