【发布时间】:2017-10-20 09:07:42
【问题描述】:
我正在开发一个 n 层应用程序,我决定在数据访问层使用存储库模式,但我不想使用任何 ORM(打算使用 ADO.net)
我无法决定如何在两个实体之间存在关系(不是父子关系)的存储库中获取数据。 例如我有客户和订单表。 “订单”表中有“客户ID”列,链接到“客户”表。
- 在获取订单时如何获取客户信息
基于 OrderID 的信息(单个或多个)? - 我们可以将一个存储库的创建实例用于另一个存储库吗?
下面是当前的代码结构。
///////////// 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; }
}
【问题讨论】:
-
你用什么来代替“任何 ORM”?应用正确的标签。在问题中发布(部分)内联代码,这些链接会在一段时间后失效。
标签: c# ado.net repository-pattern data-access-layer