是否有自动(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:
获取PatientDTOgetPatient(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;
}
谢谢。
答案 0 :(得分:1)
如何仅根据指定的属性字段创建新的动态对象并返回动态?
您需要添加以下语句:System.Dynamic
和System.ComponentModel
,以便以下工作。
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();