C# Superior TableAdapter (needs RowAdapter included)
Hello RaGEZONE,
This will make your SQL handling with tables more easily!
(not tested yet)
Why superior?
- Automatic casting an collection from a datatable with already constructed items
Code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Atomy.Adapters
{
public class TableAdapter
{
public volatile DataTable Table;
public TableAdapter(DataTable Table)
{
this.Table = Table;
}
public ICollection<T> Cast<T>()
{
ICollection<T> Output = new List<T>();
foreach (DataRow Row in Table.Rows)
{
T Object = default(T);
using(RowAdapter Adapter = new RowAdapter(Row))
{
foreach (PropertyInfo Info in typeof(T).GetProperties())
{
object Value = Adapter.Item<object>(Info.Name);
if (Value != default(object))
{
typeof(T).GetProperty(Info.Name).SetValue(Object, Value);
}
}
}
Output.Add(Object);
}
return Output;
}
}
}
How to use?
Code:
using (TableAdapter Adapter = new TableAdapter(CharacterTable))
{
ICollection<Character> Characters = Adapter.Cast<Character>();
}
YOU MUST ADD PROPERTIES TO THE CLASS YOU WANT TO CAST, THEY MUST BE NAMED THE SAME AS INSIDE THE DATABSE!