Hi,
We have built an internal tool that generates the whole data access, each table has a class the represents it's data and all the common operations.(think lightweight Entity framework).
These DataAccess objects always have a constructor that receives a connection string, and a Load function that receives a SqlDataReader.
Something like this:
class Customer
{
public string ConnStr;
public int Id;
public string Name;
Public customers(string connStr)
{
ConnStr = connStr;
}
public Customer Load(SqlDataReader)
{
if(reader.Read())
{
Id = reader["Id"].ToString();
Name = reader["Name"].ToString();
}
}
}
I want to write a utility Data Access static method that will allow me to write my SQL and get a list of objects in return, following that previous object example:
string SQL = "SELECT * FROM Customers WHERE Name=@Name";
List<Customer> customers = GetList<Customer>(connStr, SQL, new SqlParameters("@Name", "John"));
I somehow can't figure how to deal with it, I have tried interfaces but they don't allow constructors or static methods, and using generics - i can't call the methods i need to init the object(constructor + load), here is my latest try, commented out the section that doesn't work:
public static List<T> GetList<T>(string connStr, string SQL, params SqlParameter[] prms)
{
List<T> list = new List<T>();
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
SqlCommand cmd = new SqlCommand(SQL, conn);
foreach (SqlParameter param in prms)
{
cmd.Parameters.Add(param);
}
using (SqlDataReader reader = cmd.ExecuteReader())
{
//T item = new T(connStr);
//item.Load(reader);
//list.Add(item);
}
}
return list;
}
Btw, we are interested in open sourcing our DataAccess generator, it's amazing - it allow very effecient access to DB objects + creates a javascript data access layer that gives you FULL CONTROL of your DB from javascript(ofcourse this has security implications which can be managed).
If anyone here knows how to "open source" a project like this or any company that wants to join the development of this product - please feel free contacting me: [email protected]
Thanks in advance, Eytan