gpt4 book ai didi

c# - 将扩展方法限制为仅针对 EF 实体

转载 作者:太空宇宙 更新时间:2023-11-03 21:42:13 24 4
gpt4 key购买 nike

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

关于c# - 将扩展方法限制为仅针对 EF 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18767576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com