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

パトリックの答えのコード:

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 に答える