Search code examples
c#arraysjsondapperbulkupdate

How to bulk update in dapper from json struct?


Hi my data in JSON struct like this

{
  "Imei": 356980051541947,
  "sendIds": [
    {
      "Id": 13014
    },
    {
      "Id": 13190
    },
    {
      "Id": 13419
    },
    {
      "Id": 13422
    }
  ],
  "ApplicationVersion": 68,
  "GoogleId": "asdsadazxcjkh218",
  "ImagesVersion": "123:1"
}

My class is :

public class PostData
{
    public int ApplicationVersion;
    public long Imei;
    public string GoogleId;
    public string FromDate;
    public string ToDate;
    public string ImagesVersion;
    public ItemId[] SendIds;
}

public class ItemId
{
    public int Id;
}

C# code dapper update :

const string sql = "UPDATE dbo.SentMessage SET IsDelivered=1 WHERE SendID=@Id";
dapperConn.Execute(sql, postData.SendIds);

But the following error occurs when execute

Must declare the scalar variable \"@Id\

Please help me.


Solution

  • This exception occurred because your variables in your classes is Field and not Property. So you must be changed it to properties like below codes:

    public class PostData
    {
        public int ApplicationVersion { get; set; };
        public long Imei { get; set; };
        public string GoogleId { get; set; };
        public string FromDate { get; set; };
        public string ToDate { get; set; };
        public string ImagesVersion { get; set; };
        public ItemId[] SendIds { get; set; };
    }
    
    public class ItemId
    {
        public int Id { get; set; };
    }