DataReader - hardcode ordinals?

前端 未结 6 2064
执念已碎
执念已碎 2021-01-11 10:29

When returning data from a DataReader I would typically use the ordinal reference on the DataReader to grab the relevant column:

if         


        
6条回答
  •  误落风尘
    2021-01-11 10:43

    I do think that indexed fields is the better approach, if it would only be for avoiding field names changes from the underlying database, which would require a recompile of your application because you hardcoded the field name.

    For each of the fields, you will need to manually check for nulls.

    var dr = command.ExecuteQuery();
    
    if (dr.HasRows) {
        var customer = new Customer();
        // I'm assuming that you know each field's position returned from your query.
        // Where comes the importance to write all of your selected fields and not just "*" or "ALL".
        customer.Id = dr[0] == null || dr[0] == DBNull.Value ? null : Convert.ToInt32(dr[0]);
        ...
    }
    

    In addition to it, it would allow you to use reflection and make this "GetData()" method more generic providing a typeof(T) and getting the proper constructor for the proper type. The binding to the order of each columns is the only one thing some wish to avoid, but in this case, it becomes worthy.

提交回复
热议问题