将实体映射到运行时创建的 DTO
本文关键字:创建 DTO 运行时 实体 映射 | 更新日期: 2023-09-27 18:31:54
是否有一种自动映射器(automapper?)方法可以将实体映射到运行时创建的动态对象,并将属性作为参数传递?我想做一个API,客户端可以在其中选择他们想要获取的实体的属性。我的意思是:
class Patient
{
public int PatientId{ get; set; }
public string Name{ get; set; }
public string LastName{ get; set; }
public string Address{ get; set; }
...
}
getPatient(string[] properties)
{
//Return an object that has the properties passed as parameters
}
假设您只想获取带有 PatientId 和 Name 的 PatientDTO:
getPatient(new string[]{"PatientId", "Name"}
应该返回
{
"PatientId": "1234",
"Name": "Martin",
}
等等。
现在我正在使用字典,但可能有更好的方法。这是我的方法:对于单个对象:
public static Dictionary<string, object> getDTO(string[] properties, T entity)
{
var dto = new Dictionary<string, object>();
foreach (string s in properties)
{
dto.Add(s, typeof(T).GetProperty(s).GetValue(entity));
}
return dto;
}
对于对象列表:
public static List<Dictionary<string, object>> getDTOList(string[] properties, List<T> TList)
{
var dtoList = new List<Dictionary<string, object>>();
foreach(T entity in TList)
{
dtoList.Add(getDTO(properties, entity));
}
return dtoList;
}
谢谢。
如何仅基于指定的属性字段创建新的动态对象并返回动态?您需要为 : System.Dynamic
和 System.ComponentModel
添加 using 语句才能使以下内容正常工作。
public static dynamic getDTO(object entity, string[] properties)
{
IDictionary<string, object> expando = new ExpandoObject();
foreach (var p in properties)
{
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(entity.GetType()))
{
if (property.Name == p)
{
expando.Add(p, property.GetValue(entity));
break;
}
}
}
return expando as ExpandoObject;
}
调用此方法如下所示:
var patient = new Patient() { PatientId = 1, Name = "Joe", LastName = "Smith", Address = "123 Some Street'nIn Some Town, FL 32333" };
var propList = new string[] { "PatientId", "Name", "Address" };
dynamic result = getDTO(patient, propList);
Console.WriteLine("Id:{0} Name: {1}'nAddress: {2}", result.PatientId, result.Name, result.Address);
Console.ReadLine();