将实体映射到运行时创建的 dto

map entity to runtime created dto

是否有自动(自动映射器?)方法将实体映射到运行时创建的动态对象,并将属性作为参数传递?我想做一个 API,客户可以在其中 select 他们想要获取的实体的属性。 我的意思是:

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 和姓名的 PatientDTO:

getPatient(new string[]{"PatientId", "Name"} 

应该return

{
    "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;
}

谢谢。

如何仅基于指定的 属性 字段创建一个新的动态对象并返回动态对象? 您需要为以下内容添加 using 语句:System.DynamicSystem.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();