如何在运行时使用C#创建强类型数据集? [英] How do I create strongly typed dataset during runtime using C#?

查看:97
本文介绍了如何在运行时使用C#创建强类型数据集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在运行时为用户首选的目标数据库创建一个强类型的数据集。 Visual Studio具有大量的设计时支持来创建类型化的数据集。我需要在运行时自动为目标数据库生成类型化数据集的过程。

I need to create a strongly typed dataset during run-time for the user preferred target database. Visual studio has massive design time support for creating typed datasets. I need to automate the process of generating typed datasets for the target database at runtime.

它应该创建...

1。)XSD文件。

2。)表示数据库的类型化数据集

2.) Typed dataset represnting the Database

3。)

4。)每个表的TableAdapter。

4.) TableAdapters for each table.

因此,我需要在运行时生成与设计时通常使用Visual Studio的类型化数据集设计器创建的类型化数据集相同的数据集。

So I need to generate the same typed dataset at runtime which is generally created while design time using Typed dataset designer of the Visual Studio.

推荐答案

<我倾向于同意jcollum的观点,在运行时使用Typed Dataset可能是错误的方法。另一方面,如果您只想在运行时从数据库中获取结构化数据(又名DataTable),则可以使用反射从任意数据结果中创建TableAdapter。

I tend to agree with jcollum on this one, using a Typed Dataset at runtime is probably the wrong way to go. If on the other hand, you just want to be able to get structured data ( aka, a DataTable ) from a database at runtime, you could 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;
}

您可以应用相同的主体来创建结构化的DataSet并轻松地创建DataAdapter

You could apply the same principal to create a structured DataSet and easily create a DataAdapter to it.

或者我误读了您的要求。

Or perhaps I am mis-reading your requirements.

这篇关于如何在运行时使用C#创建强类型数据集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆