Search code examples
c#jsondapper

Can I remove a parameter from the Dapper DynamicParameters?


I am retrieving data from a external source. My class matches the response of the JSON. However there is an inner object inside the json. How can I remove it when I am passing it to the dynamic parameters in Dapper?

Basic structure of the class

{
   "name": "John",
   ... 30 more fields here ...

   "location": {
       "city": "abcd", 
       "zip": "87123"
    }
}

Using this like:

foreach (var result in response.results) 
{
    var parameters = new DynamicParameters();
    parameters.AddDynamicParams(result);

    // I need to remove "location" from this parameter
    // and then I can add the city and zip

    parameters.AddDynamicParams(result.location.city); // etc

    db.Execute("save_data", parameters, commandType:CommandType.StoredProcedure);
}

Solution

  • Here is a very quick way of doing it:

        var dp = new DynamicParameters();
        var ignoreList = "Id,DateAdded,Name,Address1".Split(","[0]).ToList();
        foreach (PropertyInfo prop in myObject.GetType().GetProperties())
        {
            if (!ignoreList.Contains(prop.Name))                           
                dp.Add(prop.Name, prop.GetValue(file,null));
        }