Search code examples
c#sql-serverdapper

Dapper ORM - Insert object with existing Id


I'm getting data from an API that returns this object:

{
  "status": "success",
  "message": "Sucesso",
  "count": 2,
  "items": [
    {
      "id": 18476,
      "date": "2020-12-25",
      "name": "John Doe",
      "phone": "11111111111",
      "text": "Teste de homologação DJN em produção.",
      "process": "00100522320208220501",
      "type": "D"
    }
  ]
}

When I try to insert it into the Database I get the field "id" equals to NULL.

using (var connection = new SqlConnection(Helper.GetConnectionString("cnn")))
{
    connection.Open();
    var identity = connection.Insert(my_object);
}

The "connection.Insert()" method used is from Dapper Contrib Extensions.


Solution

  • I found that you just need to use this annotation: [ExplicitKey] before the Id field.

    Reference

    using Dapper.Contrib.Extensions;
    using System;
    using System.Collections.Generic;
    
    //...
    
    [Table("your_table")]
    public class Publicacao
    {
            [ExplicitKey]
            public long Id { get; set; }
            public DateTime Date { get; set; }
            public string Name{ get; set; }
            public string Phone { get; set; }
            public string Text { get; set; }
            public string Process { get; set; }
            public string Type { get; set; }
    }