如何使用ServiceStack OrmLite - PostgreSQL从插入中返回标识值

时间:2014-08-01 19:38:56

标签: postgresql servicestack ormlite-servicestack

的NuGet: ServiceStack.4.0.25 ServiceStack.OrmLite.4.0.25 ServiceStack.OrmLite.PostgreSQL.4.0.25

鉴于此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");

和这些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; }
}

此服务使用

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())
        {

<更新>

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

            db.Save(loanApplication);// correct way

            return loanApplication.RowId;
        }
    }
}

插入后我无法检索id。我试过传递真假作为第二个参数并且都没有返回id。

谢谢你, 斯蒂芬

1 个答案:

答案 0 :(得分:4)

请参阅how to retrieve automatically inserted ids上的上一个答案,例如:

您可以使用db.Save()自动填充AutoIncrement Id,例如:

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

否则,您可以使用以下方法选择最后一个插入ID:

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

注意:selectIdentity:true只返回自动递增的ID,它不会修改loanApplication,这是db.Save()的作用。