我已经制作了一个扩展方法,用于从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。
答案 0 :(得分:3)
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;
}
}
看看此代码如何与标记接口一起使用,您可以选择将序列化方法放在接口中以避免反射并更好地控制序列化的内容以及如何编码或加密:
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;
}
答案 1 :(得分:1)
public static IDictionary<string, T> ToSerializable(this T obj) where T:Class
将缩小范围。如果您需要更多,则需要为所有实体分配标记接口并使用:
public static IDictionary<string, T> ToSerializable(this T obj) where T:IEntity