Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# function to return generic objects / entities

Tags:

In my application I need to display a list of records returned by different stored procedures. Each store procedure returns different types of records (ie the number of columns and the column type are different).

My original thought was to create a class for each type of records and create a function which would execute the corresponding stored procedure and return List< MyCustomClass>. Something like this:

  public class MyCustomClass1
  {
      public int Col1 { get; set; } //In reality the columns are NOT called Col1 and Col1 but have proper names
      public int Col2 { get; set; }
  }

    public static List<MyCustomClass1> GetDataForReport1(int Param1)
    {

        List<MyCustomClass1> output = new List<MyCustomClass1>();

        using (SqlConnection cn = new SqlConnection("MyConnectionString"))
        using (SqlCommand cmd = new SqlCommand("MyProcNameForReport1", cn))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@Param1", SqlDbType.Int).Value = Param1;

            SqlDataReader rdr=cmd.ExecuteReader();

            int Col1_Ordinal = rdr.GetOrdinal("Col1");
            int Col2_Ordinal = rdr.GetOrdinal("Col2");

            while (rdr.Read())
            {
                      output.Add(new MyCustomClass1
                      {
                          Col1 = rdr.GetSqlInt32(Col1_Ordinal).Value,
                          Col2 = rdr.GetSqlInt32(Col2_Ordinal).Value
                      });
            }
            rdr.Close();
          }

        return output;

    }

This works fine but as I don't need to manipulate those records in my client code (I just need to bind them to a graphical control in my application layer) it doesn't really make sense to do it this way as I would end up with plenty of custom classes that I wouldn't actually use. I found this which does the trick:

    public static DataTable GetDataForReport1(int Param1)
    {

        DataTable output = new DataTable();

        using (SqlConnection cn = new SqlConnection("MyConnectionString"))
        using (SqlCommand cmd = new SqlCommand("MyProcNameForReport1", cn))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@Param1", SqlDbType.Int).Value = Param1;

            output.Load(cmd.ExecuteReader());
        }

        return output;

    }

This returns a DataTable which I can bind to whatever control I use in my application layer. I'm wondering if using a DataTable is really needed.

Couldn't I return a list of objects created using anonymous classes:

    public static List<object> GetDataForReport1(int Param1)
    {

        List<object> output = new List<object>();

        using (SqlConnection cn = new SqlConnection("MyConnectionString"))
        using (SqlCommand cmd = new SqlCommand("MyProcNameForReport1", cn))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@Param1", SqlDbType.Int).Value = Param1;

            SqlDataReader rdr=cmd.ExecuteReader();

            int Col1_Ordinal = rdr.GetOrdinal("Col1");
            int Col2_Ordinal = rdr.GetOrdinal("Col2");

            while (rdr.Read())
            {
                      output.Add(new 
                      {
                          Col1 = rdr.GetSqlInt32(Col1_Ordinal).Value,
                          Col2 = rdr.GetSqlInt32(Col2_Ordinal).Value
                      });
            }
            rdr.Close();
          }

        return output;

    }

Any other ideas? Basically I just want the function to return 'something' which I can bind to a graphical control and I prefer not to have to create custom classes as they wouldn’t really be used. What would be the best approach?

like image 659
Anthony Avatar asked Nov 27 '09 10:11

Anthony


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C language basics?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


2 Answers

The good news is: this isn't the first time the entities vs datasets issue has come up. It's a debate much older than my own programming experience. If you don't want to write DTO's or custom entities then your options are DataTables/DataSets or you could reinvent this wheel again. You wouldn't be the first and you won't be the last. The argument for DTO's/Entities is that you don't have the performance overheads that you get with DataSets. DataSets have to store a lot of extra information about the datatypes of the various columns, etc...

One thing, you might be happy to hear is that if you go the custom entity route and you are happy for your object property names to match the column names returned by your sprocs, you can skip writing all those GetDataForReport() mapping functions where you are using GetOrdinal to map columns to properties. Luckily, some smart monkeys have properly sussed that issue here.

EDIT: I was researching an entirely different problem today (binding datasets to silverlight datagrids) and came across this article by Vladimir Bodurov, which shows how to transform an IEnumerable of IDictionary to an IEnumerable of dynamically created objects (using IL). It occured to me that you could easily modify the extension method to accept a datareader rather than the IEnumerable of IDictionary to solve your issue of dynamic collections. It's pretty cool. I think it would accomplish exactly what you were after in that you no longer need either the dataset or the custom entities. In effect you end up with a custom entity collection but you lose the overhead of writing the actual classes.

If you are lazy, here's a method that turns a datareader into Vladimir's dictionary collection (it's less efficient than actually converting his extension method):

public static IEnumerable<IDictionary> ToEnumerableDictionary(this IDataReader dataReader)
{
    var list = new List<Dictionary<string, object>>();
    Dictionary<int, string> keys = null;
    while (dataReader.Read())
    {
        if(keys == null)
        {
            keys = new Dictionary<int, string>();
            for (var i = 0; i < dataReader.FieldCount; i++)
                keys.Add(i, dataReader.GetName(i));
        }
        var dictionary = keys.ToDictionary(ordinalKey => ordinalKey.Value, ordinalKey => dataReader[ordinalKey.Key]);
        list.Add(dictionary);
    }
    return list.ToArray();
}
like image 65
grenade Avatar answered Oct 12 '22 09:10

grenade


If you're going to XmlSerialize them and want that to be efficient, they can't be anonymous. Are you going to send back the changes? Anonymous classes wont be much use for that.

If you're really not going to do anything with the data other than gridify it, a DataTable may well be a good answer for your context.

In general, if there's any sort of interesting business login going on, you should be using Data Transfer Objects etc. rather than just ferrying around grids.

like image 41
Ruben Bartelink Avatar answered Oct 12 '22 08:10

Ruben Bartelink