I am trying to make an invoice managing application.
When creating DAL object, I have to repeat Add
and Delete
functions for every table.
For example:
public class MyDBProcessor :IMyDBProcessor {
tpEntities tp=new tpEntities();
public void AddCustomerToDB(tblCustomers Customer) { tp.tblCustomers.Add(Customer); tp.SaveChanges();}
public void AddOrderToDB(tblOrders Order) { tp.tblOrders.Add(Order); tp.SaveChanges(); }
public tblCustomers GetCustomerFromDB(string CustomerID) { return tp.tblCustomers.Where(x => x.ID == CustomerID); }
public tblOrders GetOrderFromDB(string OrderID) { return tp.tblOrders.Where(x => x.ID == OrderID); }
}
It is very frustrating because there are so many tables. I want to change DAL interface like this:
public interface IMyGenericDBProcessor {
void AddToDB<T>(T Record);
T GetFromDB<T>(int RecordID);
}
So, when I change db engine MySQL to SQL Server or vice versa. How can I write a class that implemets IMyGenericDBProcessor
?
Thank you,
Adding is easy:
public interface IMyGenericDBProcessor
{
void AddToDB<T>(T Record) where T : class;
}
public class MyDBProcessor : IMyGenericDBProcessor
{
public void AddToDB<T>(T record) where T : class
{
using(var tp = new tpEntities())
tp.Set<T>().Add(record);
}
}
GetFromDb would be more complicated because you'd have to determine, based on the entity context's metadata, which property comprises the ID, and then construct an expression tree based on that.