且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Asp.Net MVC 中将数据表转换为 POCO 对象?

更新时间:2023-12-02 16:35:58

将每个 DataRow 传递给类构造函数(或使用 getter/setter)并将每一列转换为相应的属性.小心处理可为空的列以正确提取它们.

Pass each DataRow into the class constructor (or use getters/setters) and translate each column into the corresponding property. Be careful with nullable columns to extract them properly.

  public class POCO
  {
       public int ID { get; set; }
       public string Name { get; set; }
       public DateTime? Modified { get; set; }
       ...

       public POCO() { }

       public POCO( DataRow row )
       {
            this.ID = (int)row["id"];
            this.Name = (string)row["name"];
            if (!(row["modified"] is DBNull))
            {
                 this.Modified = (DateTime)row["modified"];
            }
            ...
       }
  }