我的 Entity Framework 实体和我序列化/反序列化的 JSON 对象之间有一个中间对象,以便导入和导出到文本文件。
当我从实体框架导出时,我使用以下代码遍历实体类型属性...如果实体中的属性与我拥有的枚举中的属性匹配,则该属性将保存到 JSON 对象。这可以防止实体特定属性弄乱我的 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());
}
虽然上面的代码有效,但我想不出类似的方法来做相反的事情。从 JSON 中读取时,我在字典中有属性/值。我知道我可以遍历 EF 实体的属性并搜索字典是否包含这样的键:
var blockProperties = typeof(FixedLengthBlock).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in blockProperties)
{
if (block.Properties.ContainsKey(property.Name))
{
???????What goes here??????
}
}
如何将匹配的属性放入我为接收信息而创建的新实体中。我真的很想避免使用大的 switch 语句。
我的 Json 对象如下所示:
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>();
}
}