I have an intermediary object between my Entity Framework entities and a JSON object that I serialize/deserialize in order to import and export to a text file.
When I am exporting from the entity framework I use the following code to iterate through the entity types properties…If the property in the entity matches the property from an enum that I have, the property gets saved to the JSON object. This stops entity specific properties from cluttering up my JSON.
var blockProperties = typeof(FixedLengthBlock).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in blockProperties)
{
if (Enum.GetNames(typeof(ModuleSettingEnum)).Contains(property.Name.ToLower()) && property.GetValue((FixedLengthBlock)element, null) != null)
blockJsonEntity.Properties.Add(property.Name, property.GetValue((FixedLengthBlock)element, null).ToString());
}
While the above code works, I cannot think of a similar way to do the opposite. When reading back from JSON I have the properties/values in a dictionary. I know that I can run through the properties of the EF Entity and search the dictionary if it contains a key like this:
var blockProperties = typeof(FixedLengthBlock).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in blockProperties)
{
if (block.Properties.ContainsKey(property.Name))
{
???????What goes here??????
}
}
How do I get the matched property into the newly created entity I’ve made to receive the information. I’d really like to avoid a large switch statement.
My Json object looks like this:
public class JsonEntity
{
public string Name { get; set; }
public string Type { get; set; }
public Dictionary<string, string> Properties { get; set; }
public List<JsonEntity> SubEntities { get; set; }
public JsonEntity()
{
Properties = new Dictionary<string, string>();
}
}
Okay, so if we’re deserializing into the same type let’s try this: