我正在处理Json文件并向数据库添加值,但是有没有任何方法可以动态构建Payload,只包括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();
我使用的Json文件是动态的,例如,如果我对系统中的所有4列进行了更新,那么它将生成我可以用于Paylod的格式,但如果我对第1列进行更新,那么Json只包含第1列的Key,那么它就不能用于我的Paylod,因为代码将为第2列、第3列和第4列抛出空异常
假设Aattributes
是Dictionary<string, string>
,您可以执行以下操作:
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);
}
}