I have this model:
namespace SomeApp.Models
{
public class FirstModel
{
public int uid { get; set; }
public string? id { get; set; }
public string? firstname { get; set; }
public string? lastname { get; set; }
}
}
whose fields I need to convert to a dictionary or JSON object in another model. I'm using the GetFields
Method.
namespace SomeApp.Models
{
public class SecondModel
{
// other fields
public Dictionary<string, string> FirstModelTransfer { get; set; }
public void SetFirstModelTransfer(FirstModel firstModel)
{
FieldInfo[] firstModelFields = typeof(FirstModel).GetFields();
Dictionary<string, string> dict = new();
foreach (var firstModelField in firstModelFields)
{
string fieldName = firstModelField.Name;
string fieldValue = firstModelField.GetValue(fieldName).ToString();
dict[fieldName] = fieldValue;
}
FirstModelTransfer = dict;
}
}
}
I want the result to look like
{
// other fields
"FirstModelTransfer": {
"firstname": "Sample firstname",
"lastname": "Sample lastname"
}
}
But currently, it looks like this,
{
// other fields
"FirstModelTransfer": {
"additionalProp1": "string",
"additionalProp2": "string",
"additionalProp3": "string"
}
}
I don't know if this matters but:
services.AddDbContext<SecondModelsContext>();
services.AddDbContext<FirsModelsContext>();
This is the ordering of the dbContexts in which each model was registered.