我制作了一个扩展方法,用于从 EF 实体制作可序列化的字典:
public static class Extensions
{
public static IDictionary<string, object> ToSerializable(this object obj)
{
var result = new Dictionary<string, object>();
foreach (var property in obj.GetType().GetProperties().ToList())
{
var value = property.GetValue(obj, null);
if (value != null && (value.GetType().IsPrimitive
|| value is decimal || value is string || value is DateTime
|| value is List<object>))
{
result.Add(property.Name, value);
}
}
return result;
}
}
我是这样使用它的:
using(MyDbContext context = new MyDbContext())
{
var someEntity = context.SomeEntity.FirstOrDefault();
var serializableEntity = someEntity.ToSerializable();
}
我想知道是否有任何方法可以将其限制为仅在我的实体上可用,而不是在所有 object:s 上可用。
请您参考如下方法:
Patryk 的答案代码:
public interface ISerializableEntity { };
public class CustomerEntity : ISerializableEntity
{
....
}
public static class Extensions
{
public static IDictionary<string, object> ToSerializable(
this ISerializableEntity obj)
{
var result = new Dictionary<string, object>();
foreach (var property in obj.GetType().GetProperties().ToList())
{
var value = property.GetValue(obj, null);
if (value != null && (value.GetType().IsPrimitive
|| value is decimal || value is string || value is DateTime
|| value is List<object>))
{
result.Add(property.Name, value);
}
}
return result;
}
}
看到此代码如何与标记接口(interface)一起工作,您可以选择将序列化方法放在接口(interface)中以避免反射,并更好地控制序列化的内容以及编码或加密的方式:
public interface ISerializableEntity
{
Dictionary<string, object> ToDictionary();
};
public class CustomerEntity : ISerializableEntity
{
public string CustomerName { get; set; }
public string CustomerPrivateData { get; set; }
public object DoNotSerializeCustomerData { get; set; }
Dictionary<string, object> ISerializableEntity.ToDictionary()
{
var result = new Dictionary<string, object>();
result.Add("CustomerName", CustomerName);
var encryptedPrivateData = // Encrypt the string data here
result.Add("EncryptedCustomerPrivateData", encryptedPrivateData);
}
return result;
}
