繁体   English   中英

将扩展方法限制为仅定位EF实体

[英]Limiting extension method to target EF Entities only

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

看看此代码如何与标记接口一起使用,您可以选择将序列化方法放在接口中以避免反射并更好地控制序列化的内容以及如何编码或加密:

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;
}
public static IDictionary<string, T> ToSerializable(this T obj) where T:Class

将它缩小一点。 如果您需要更多,则需要为所有实体分配标记接口并使用:

public static IDictionary<string, T> ToSerializable(this T obj) where T:IEntity

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM