1

我制作了一个扩展方法,用于从 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。

4

2 回答 2

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;
}
于 2013-09-12T15:11:54.013 回答
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
于 2013-09-12T15:08:38.270 回答