How do I create a typed dataset at runtime using C #?

I need to create a strongly typed dataset at runtime for the user's preferred target database. Visual Studio has tremendous design-time support for creating typed datasets. I need to automate the process of creating typed datasets for a target database at runtime.

He must create ...

1.) XSD file.

2.) Typed dataset representing a database

3.) Typed wrappers for all tables and database columns in tables.

4.) TableAdapters for each table.

So, I need to create the same typed dataset at runtime that I would normally create at design time using Visual Studio's typed dataset designer.

0


a source to share


3 answers


I tend to agree with jcollum on this, using Typed Dataset at runtime is probably not the way to go. If, on the other hand, you just want to get structured data (like a DataTable) from the database at runtime, you can use reflection to create a TableAdapter from an arbitrary data result.

var results = (from data in db.SomeTable select data).ToArray();
DataTable dt = ObjectArrayToDataTable(results);
// At this point you have a properly structure DataTable.

// Here is your XSD, if absolutely needed.
dt.WriteXMLSchema("c:\somepath\somefilename.xsd");

private static System.Data.DataTable ObjectArrayToDataTable(object[] data)
{
    System.Data.DataTable dt = new System.Data.DataTable();
    // if data is empty, return an empty table
    if (data.Length == 0) return dt;

    Type t = data[0].GetType();
    System.Reflection.PropertyInfo[] piList = t.GetProperties();

    foreach (System.Reflection.PropertyInfo p in piList)
    {
        dt.Columns.Add(new System.Data.DataColumn(p.Name, p.PropertyType));
    }

    object[] row = new object[piList.Length];

    foreach (object obj in data)
    {
        int i = 0;
        foreach (System.Reflection.PropertyInfo pi in piList)
        {
            row[i++] = pi.GetValue(obj, null);
        }
        dt.Rows.Add(row);
    }

    return dt;
}

      



You can apply the same principle to create a structured DataSet and easily create a DataAdapter for it.

Or perhaps I am reading your requirements incorrectly.

+2


a source


Perhaps you can use XSD.EXE

. Run it from your program ...



+2


a source


Given my past experience with typed datasets - and all their attendant glitches and issues - I highly recommend that you investigate this with an ORM map. In other words, run away from typed datasets.

+1


a source







All Articles