I'm processing Json file and adding values to database, however is there any way to build Payload dynamically to only include columns presented in Json?
code payloadMessageContext.Update(new Payload {
Id = 1,
column1 = Attributes.Where(x => x.Key == "column1")?.FirstOrDefault().Value.ToString(),
column2 = Attributes.Where(x => x.Key == "column2")?.FirstOrDefault().Value.ToString(),
column3 = Attributes.Where(x => x.Key == "column3")?.FirstOrDefault().Value.ToString(),
column4 = Attributes.Where(x => x.Key == "column4")?.FirstOrDefault().Value.ToString(),
});
await payloadMessageContext.SaveChangesAsync();
The Json file I'm using is dynamic for example if I made an update to all 4 columns in my system then it will generate the format I can use for my Paylod, but if I made an update to column1 then Json contain only Key for column1, then it can't be used for my Paylod as the code will throw null exception for column2, column3 and column4
Assuming Aattributes
is Dictionary<string, string>
you can do something like this:
static void Main(string[] args)
{
var Aattributes = new Dictionary<string, string>
{
["Column1"] = "NewColumn1",
["Column3"] = "NewColumn3",
};
var payload = new Payload();
Set(Aattributes, "Column1", payload, (target, val) => target.Column1 = val);
Set(Aattributes, "Column2", payload, (target, val) => target.Column2 = val);
Set(Aattributes, "Column3", payload, (target, val) => target.Column3 = val);
Set(Aattributes, "Column4", payload, (target, val) => target.Column4 = val);
}
private static void Set<TTarget>(IDictionary<string, string> source, string key, TTarget target, Action<TTarget, string> setter)
{
if (source.ContainsKey(key))
{
var value = source[key];
setter(target, value);
}
}