I have recently come across a very simple Typed DataTable (without using a .XSD)(I've lost author's URL so I can't credit him) but it looks like there's a lot of duplicated code (Such as the Add/Remove/GetNewRow methods).
I've tried to push the repetitive methods into a super class, but I have issues due to the Employee needing to be generic. I was hoping to get StackOverflow's collective hive mind to suggest some ideas to clean this up? (If it's even possible at all?)
using System;
using System.Data;
using System.Collections;
using System.Data.SqlClient;
namespace TypedDataSet {
public class Employees : DataTable {
protected SqlDataAdapter _adapter;
public Employees() {
string connectionString = TypedDataSet.Properties.Settings.Default.ConnectionString;
_adapter = new System.Data.SqlClient.SqlDataAdapter("SELECT Id, Firstname, Surname FROM Employee", connectionString);
_adapter.Fill(this);
}
public Employee this[int index] {
get { return (Employee)Rows[index]; }
}
public void Add(Employee row) {
Rows.Add(row);
}
public void Remove(Employee row) {
Rows.Remove(row);
}
public Employee GetNewRow() {
Employee row = (Employee)NewRow();
return row;
}
protected override DataRow NewRowFromBuilder(DataRowBuilder builder) {
return new Employee(builder);
}
public IEnumerator GetEnumerator() {
return Rows.GetEnumerator();
}
protected override Type GetRowType() {
return typeof(Employee);
}
}
public class Employee : DataRow {
internal Employee(DataRowBuilder builder)
: base(builder) {
}
public Int64 Id {
get { return (Int64)base["Id"]; }
set { base["Id"] = value; }
}
public string FirstName {
get { return (string)base["Firstname"]; }
set { base["Firstname"] = value; }
}
public string Surname {
get { return (string)base["Surname"]; }
set { base["Surname"] = value; }
}
}
}