How can I map the results of a sql query onto objects?

后端 未结 7 1666
灰色年华
灰色年华 2021-02-01 20:37

Currently, I am using something like this:

    try
    {
      dr = SQL.Execute(sql);

      if(dr != null) {
         while(dr.Read()) {
           CustomObject         


        
7条回答
  •  执念已碎
    2021-02-01 21:07

    One simple solution would be to make a constructor for your CustomObject that takes a DataRow (from the example, so if it's another class, please correct me).

    And in your new constructor, do as you do in your own example.

    public CustomObject(DataRow row)
    {
        Key = row[0].ToString();
        // And so on...
    }
    

    One other way would be to introduce generics, and make a new function in your SQL-class

    Example (Took code from Passing arguments to C# generic new() of templated type):

    // This function should reside in your SQL-class.
    public IEnumerable ExecuteObject(string sql)
    {
        List items = new List();
        var data = ExecuteDataTable(sql); // You probably need to build a ExecuteDataTable for your SQL-class.
        foreach(var row in data.Rows)
        {
            T item = (T)Activator.CreateInstance(typeof(T), row);
            items.Add(item);
        }
        return items;
    }
    

    Example usage:

    public IEnumerable GetCustomObjects()
    {
        return SQL.ExecuteObject("SELECT * FROM CustomObject");
    }
    

    I have tested this code in LinqPad, it should work.

提交回复
热议问题