I am developing an n-tier application and I have decided to use the Repository Pattern in Data Access Layer but I don't want to use any ORM(going to use ADO.net)
I am not able to decide how to fetch the data in repository where there is relation between 2 entites(not parent child relationship). For e.g. I have Customer and Order table. There is "CustomerID" column in "Order" table which is linked to "Customer" table.
- How to fetch the Customer Information while I am fetching Orders
Information(single or Multiple) based on OrderID? - Can we use create instance of one repository into another?
Below is the current code structure.
///////////// Abstract Class for Common Functionality////
public abstract class BaseRepository<T> where T : class
{
private static SqlConnection sqlConnection;
protected string DatabaseName { get; set; }
protected string ConnectionString;
public delegate T CallBack(SqlDataReader reader);
public BaseRepository()
{
ConnectionString = Convert.ToString(ConfigurationManager.ConnectionStrings["TestDB"]);
sqlConnection = new SqlConnection(ConnectionString);
}
protected abstract T PopulateRecord(SqlDataReader reader);
protected IEnumerable<T> GetRecords(SqlCommand command)
{
var list = new List<T>();
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
command.Connection = connection;
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader != null)
{
while (reader.Read())
{
list.Add(PopulateRecord(reader));
}
}
} // reader closed and disposed up here
} //connection closed and disposed here
return list;
}
}
////////////////// Repository Class //////////////////////////
public class OrderRepository : BaseRepository<Order>, IRepository<Order>
{
protected override Order PopulateRecord(SqlDataReader reader)
{
return new Order
{
OrderID = reader.GetIntVal("OrderID"),
OrderDate = reader.GetDateTimeVal("OrderDate"),
ProductInfo= // How to Populate Product Information which is in another repository
CustomerInfo = // How to Populate Customer Information which is in another repository
};
}
public IEnumerable<Order> GetAll()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "GetOrders";
cmd.CommandType = CommandType.StoredProcedure;
return GetRecords(cmd);
}
}
/////////////// Entity Class ////////////////////
public class Order {
public int OrderID { get; set; }
public DateTime OrderDate { get; set; }
public Customer ProductInfo { get; set; }
public Product CustomerInfo { get; set; }
}
public class Customer {
public int CustomerID { get; set; }
public string CustomerName { get; set; }
}
public class Product {
public int ProductID { get; set; }
public string ProductName { get; set; }
}