如何将模型类对象转换为数据表

Zhu*_*Zhu -1 .net c# asp.net-web-api asp.net-core

我是 c# 新手,我想在 Web API 中将模型类对象转换为 DataTable。

模型类

 public class Employee_Master_Model
    {
        public string UserType { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string MiddleName { get; set; }
        public string Mobile { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
        public bool IsActive { get; set; }
        public int EmployeeId { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

控制器:

 public async Task<IActionResult> CreateEmployee([FromBody] Employee_Master_Model employee_Master_Model)
        {
            try
            {
              // Need to convert the object (employee_Master_Model) to DataTable
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Run Code Online (Sandbox Code Playgroud)

尝试几个小时都无法完成。谁能帮我解决这个问题。

rad*_*rad 5

通过以下代码,您可以动态创建数据表列:

PropertyDescriptorCollection props = 
    TypeDescriptor.GetProperties(typeof(Employee_Master_Model));
DataTable dt = new DataTable();
foreach (PropertyDescriptor p in props)
    dt.Columns.Add(p.Name, p.PropertyType);
Run Code Online (Sandbox Code Playgroud)

其余的只是将实体字段值复制到数据表列。