Skip to content

Instantly share code, notes, and snippets.

@takiru
Last active May 11, 2017 08:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takiru/308ddc783767d7b59a323300af20d8ad to your computer and use it in GitHub Desktop.
Save takiru/308ddc783767d7b59a323300af20d8ad to your computer and use it in GitHub Desktop.
Injection in the Entity Class from DataTable or DataRow.
using System.Data;
namespace WindowsFormsApp1
{
public static class DataRowExtensions
{
public static T ToEntity<T>(this DataRow row) where T : new()
{
var resultData = new T();
var t = resultData.GetType();
var pis = t.GetProperties();
foreach (var pi in pis)
{
pi.SetValue(resultData, row[pi.Name]);
}
return resultData;
}
}
}
using System.Collections.Generic;
using System.Data;
namespace WindowsFormsApp1
{
public static class DataTableExtensions
{
public static IEnumerable<T> AsEnumerableEntity<T>(this DataTable dt) where T : new()
{
int i = 0;
while (i < dt.Rows.Count)
{
var r = dt.Rows[i].ToEntity<T>();
i++;
yield return r;
}
}
}
}
using System;
using System.Data;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Prepare DataTable Data
var dt = new DataTable("SampleTable");
dt.Columns.AddRange(new DataColumn[] {
new DataColumn("ID", typeof(int)),
new DataColumn("Name", typeof(string))
});
dt.Rows.Add(new object[] { 1, "aaa" });
dt.Rows.Add(new object[] { 2, "bbb" });
dt.Rows.Add(new object[] { 3, "ccc" });
// from DataRow
foreach (DataRow row in dt.Rows)
{
var user = row.ToEntity<MemberData>();
Console.WriteLine("ID = {0}, Name = {1}", user.ID, user.Name);
}
// from DataTable
foreach(var row in dt.AsEnumerableEntity< MemberData>())
{
Console.WriteLine("ID = {0}, Name = {1}", row.ID, row.Name);
}
}
}
}
namespace WindowsFormsApp1
{
class MemberData
{
public int ID { get; set; } = 0;
public string Name { get; set; } = "";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment