【发布时间】:2012-01-09 18:41:55
【问题描述】:
我对存储库模式还很陌生,我想正确地做到这一点。我也在尝试使用控制反转(也是新的)。
我想确保我正确使用了存储库模式。
我选择这个作为我的存储库的基本接口示例。
public interface IRepository<T> where T : class
{
IEnumerable<T> Find(Expression<Func<T, bool>> where);
IEnumerable<T> GetAll();
void Create(T p);
void Update(T p);
}
IPaymentRepository 用于 IRepository 的扩展(虽然我不明白如果我有上面的 Find 方法我为什么需要它)
public interface IPaymentRepository : IRepository<Payment>
{
}
PaymentRepository 只是读取一个文本文件并构建一个 POCO。
public class PaymentRepository : IPaymentRepository
{
#region Members
private FileInfo paymentFile;
private StreamReader reader;
private List<Payment> payments;
#endregion Members
#region Constructors
#endregion Constructors
/// <summary>
/// Initializes a new instance of the <see cref="PaymentRepository"/> class.
/// </summary>
/// <param name="paymentFile">The payment file.</param>
public PaymentRepository(FileInfo paymentFile)
{
if (!paymentFile.Exists)
throw new FileNotFoundException("Could not find the payment file to process.");
this.paymentFile = paymentFile;
}
#region Properties
#endregion Properties
#region Methods
public IEnumerable<Payment> Find(Expression<Func<Payment, bool>> where)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets all payments from payment file.
/// </summary>
/// <returns>Collection of payment objects.</returns>
public IEnumerable<Payment> GetAll()
{
this.reader = new StreamReader(this.paymentFile.FullName);
this.payments = new List<Payment>();
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
Payment payment = new Payment()
{
AccountNo = line.Substring(0, 11),
Amount = double.Parse(line.Substring(11, 10))
};
this.payments.Add(payment);
}
return this.payments;
}
public void Create(Payment p)
{
throw new NotImplementedException();
}
public void Update(Payment p)
{
throw new NotImplementedException();
}
#endregion Methods
我想知道如何实现 Find 方法。我假设我会调用 GetAll 并为存储库构建一个内部缓存。例如,我想查找所有付款超过 50 美元的帐户。
【问题讨论】:
-
小提示:使用 File.ReadAllLines 获取行的字符串[]。
-
我没用过那个方法。您看到的是性能提升还是代码行数减少了?
标签: c#-4.0 repository repository-pattern