类到DataSet / DataSet到类 [英] Class to DataSet / DataSet to class

查看:151
本文介绍了类到DataSet / DataSet到类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我想创建一个数据库处理程序来动态处理数据库。说我有一个类型的字段类型String,int,bool,String,并希望将这个类转换为一个表,所有的字段类型转换为数据集的字段?



另外,我可以创建几个类继承:System.Data.DataSet,System.Data.DataTable System.Data.DataRow和一些适配器来处理它。



我知道当你进入设计模式并创建一个数据集,代码真的很难做出来,当你看它。但是不应该有可能通过使用这些对象和创建类来处理它们能够动态创建数据库。它不会得到一个设计器视图,但Database.AddTable(新表(Field1,Field2,Field3))应该做同样在设计器模式下做图形。



任何想法?



主要想法是灵活,我可以采取任何类,并将其转换成一个表的行与每个对象



这是只是一个简单的类,我在最后一个小时,我是想正确的方式吗?仍然需要能够添加DataSet到* .mdf / * .sdf文件,我该怎么做? >

  public class DataAccess 
{

SqlConnection连接;
DataSet dataSet ;

public DataAccess(String databaseName,String connectionStr)
{
dataSet = new DataSet(databaseName);
connection = new SqlConnection(connectionStr);
}

public void AddTable< T>(String tableName)
{
dataSet.Tables.Add(new DBTable< T&
}

public void AddRow< T>(String tableName,T row)
{
((DBTable T)dataSet.Tables [tableName])。 AddRow T(row);
}

public List< C> GetRows< T,C>(String tableName,String columnName)
{
return((DBTable< T>)dataSet.Tables [tableName])。
}

public String GetXML()
{
return dataSet.GetXml();
}

#region方法属性

public int ColumnCount(String tableName)
{
for(int i = 0; i< ; dataSet.Tables.Count; i ++)
{
if(dataSet.Tables [i] .TableName == tableName)
{
return dataSet.Tables [i] .Columns 。计数;
}
}

return 0;
}

#endregion


}

public class DBTable< T> :System.Data.DataTable
{
public DBTable(String tableName):base(tableName)
{

PropertyInfo [] properties = typeof(T).GetProperties ();

for(int i = 0; i< properties.Length; i ++)
{
try
{
AddColumn(properties [i]。名称,属性[i] .PropertyType);
}
catch {}
}

}

private void AddColumn(String name,Type t)
{
this.Columns.Add(new DataColumn(name,t,null,MappingType.Attribute));
}

public void AddRow< T>(T obj)
{
PropertyInfo [] properties = typeof(T).GetProperties

if(properties.Length == this.Columns.Count)
{

bool valid = true;

for(int i = 0; i< properties.Length; i ++)
{
if(properties [i] .PropertyType!= this.Columns [i]。 DataType)
{
valid = false;
}
}

if(valid)
{
object [] p = new object [this.Columns.Count];

for(int i = 0; i< properties.Length; i ++)
{
p [i] = properties [i] .GetValue(obj,null);
}

this.Rows.Add(p);
}
}
}

public List< T> GetRow< T>(String columnName)
{

List< T> objects = new List< T>();

for(int i = 0; i< this.Rows.Count; i ++)
{
objects.Add((T)this.Rows [i] [this .columns [columnName]]);
}

返回对象;

}
}


解决方案

Petapoco 图书馆是您要寻找的内容。



您可能需要查看通用列表和LINQ的一些位: Petapoco方法不使用 DataSet DataTable 对象。



正如leppie所说,这不是这个问题的答案。因此,创建与类匹配的DataTable对象可以通过这种方式实现:

  public static DataTable CreateDataTable< T> b $ b {
var dt = new DataTable();

var propList = typeof(T).GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

foreach(propList中的MemberInfo信息)
{
if(info是PropertyInfo)
dt.Columns.Add(new DataColumn(info.Name, PropertyInfo).PropertyType));
else if(info是FieldInfo)
dt.Columns.Add(new DataColumn(info.Name,(info as FieldInfo).FieldType));
}

return dt;
}

如果您希望以后填写此表:

  public static void FillDataTable< T>(DataTable dt,List< T> items)
{
var propList = typeof .GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

foreach(T t in items)
{
var row = dt.NewRow();
foreach(propList中的MemberInfo信息)
{
if(info是PropertyInfo)
row [info.Name] =(infoIn PropertyInfo).GetValue(t,null);
else if(info是FieldInfo)
row [info.Name] =(info FieldInfo).GetValue(t);
}
dt.Rows.Add(row);
}
}

您希望您的 DataTable 对象在同一时间创建和填充。


Right now I'm trying to create a database handler that handles databases dynamically. Say I have a class of fieldtypes "String, int, bool, String" and want to turn this class into a table and all the fieldtypes into "fields" of a dataset?

How can I do that?

Also, can I create a few classes that inherits: "System.Data.DataSet", "System.Data.DataTable", "System.Data.DataRow", and some sort of Adapter to handle it.

I know when you go into design mode and create a dataset the code is really hard to make out when you look at it. But shouldn't it be possible by using these objects and creating classes that handle them to be able to "create" database dynamically. It wouldn't get a "Designer View" but, Database.AddTable(new Table("Field1", "Field2, "Field3")) should do the same as you do graphically in Designer mode.

Any ideas?

The main idea is that it's flexible and I can take whatever class and turn it into a table of rows with each object of this class' field values as database fields.

UPDATE

This is just a simple class that I made in the last hour, am I thinking the right way? Still need to be able to add DataSet to the *.mdf / *.sdf file, how do I do that?

public class DataAccess
{

    SqlConnection connection;
    DataSet dataSet;

    public DataAccess(String databaseName, String connectionStr)
    {
        dataSet = new DataSet(databaseName);
        connection = new SqlConnection(connectionStr);
    }

    public void AddTable<T>(String tableName)
    {
        dataSet.Tables.Add(new DBTable<T>(tableName));
    }

    public void AddRow<T>(String tableName, T row)
    {
        ((DBTable<T>)dataSet.Tables[tableName]).AddRow<T>(row);
    }

    public List<C> GetRows<T, C>(String tableName, String columnName)
    {
        return ((DBTable<T>)dataSet.Tables[tableName]).GetRow<C>(columnName);
    }

    public String GetXML()
    {
        return dataSet.GetXml();
    }

    #region METHOD PROPERTIES

    public int ColumnCount(String tableName)
    {
        for (int i = 0; i < dataSet.Tables.Count; i++)
        {
            if (dataSet.Tables[i].TableName == tableName)
            {
                return dataSet.Tables[i].Columns.Count;
            }
        }

        return 0;
    }

    #endregion


}

public class DBTable<T> : System.Data.DataTable
{
    public DBTable(String tableName) : base(tableName)
    {

        PropertyInfo[] properties = typeof(T).GetProperties();

        for (int i = 0; i < properties.Length; i++)
        {
            try
            {
                AddColumn(properties[i].Name, properties[i].PropertyType);
            }
            catch { }
        }

    }

    private void AddColumn(String name, Type t)
    {
        this.Columns.Add(new DataColumn(name, t, null, MappingType.Attribute));
    }

    public void AddRow<T>(T obj)
    {
        PropertyInfo[] properties = typeof(T).GetProperties();

        if (properties.Length == this.Columns.Count)
        {

            bool valid = true;

            for (int i = 0; i < properties.Length; i++)
            {
                if (properties[i].PropertyType != this.Columns[i].DataType)
                {
                    valid = false;
                }
            }

            if (valid)
            {
                object[] p = new object[this.Columns.Count];

                for (int i = 0; i < properties.Length; i++)
                {
                    p[i] = properties[i].GetValue(obj, null);
                }

                this.Rows.Add(p);
            }
        }
    }

    public List<T> GetRow<T>(String columnName)
    {

        List<T> objects = new List<T>();

        for (int i = 0; i < this.Rows.Count; i++)
        {
            objects.Add((T)this.Rows[i][this.Columns[columnName]]);
        }

        return objects;

    }
}

解决方案

The Petapoco library is what you are looking for. You can save and retrieve data from database to POCO objects and vice-versa very easily.

You might have to take a look about generic lists and some bits of LINQ : the Petapoco approach does not use DataSet nor DataTable objects.

As leppie stated, this is not quite the answer to the question. So, creating a DataTable object that matches a class could be achieved this way :

public static DataTable CreateDataTable<T>()
{
    var dt = new DataTable();

    var propList = typeof(T).GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

    foreach(MemberInfo info in propList)
    {
        if(info is PropertyInfo)
            dt.Columns.Add(new DataColumn(info.Name, (info as PropertyInfo).PropertyType));
        else if(info is FieldInfo)
            dt.Columns.Add(new DataColumn(info.Name, (info as FieldInfo).FieldType));
    }

    return dt;
}

If you wish to fill this table afterwards :

public static void FillDataTable<T>(DataTable dt, List<T> items)
{
    var propList = typeof(T).GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

    foreach(T t in items)
    {
        var row = dt.NewRow();
        foreach(MemberInfo info in propList)
        {
            if (info is PropertyInfo)
                row[info.Name] = (info as PropertyInfo).GetValue(t, null);
            else if (info is FieldInfo)
                row[info.Name] = (info as FieldInfo).GetValue(t);
        }
        dt.Rows.Add(row);
    }
}

You could also mix both features in a single function if you wish your DataTable object to be created and filled in the same time.

这篇关于类到DataSet / DataSet到类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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