Nov*_*vus 5 repository repository-pattern c#-4.0
我对存储库模式相当陌生,我想正确地做到这一点。我也在尝试使用控制反转(也是新的)。
我想确保我正确使用了存储库模式。
我选择它作为我的存储库的基本接口示例。
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);
}
Run Code Online (Sandbox Code Playgroud)
IPaymentRepository 用于 IRepository 的扩展(虽然我不明白如果我有上面的 Find 方法,我为什么需要它)
public interface IPaymentRepository : IRepository<Payment>
{
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
我想知道如何实现 Find 方法。我假设我会调用 GetAll 并为存储库构建一个内部缓存。例如,我想查找所有付款超过 50 美元的帐户。
使用您当前的 IRepository 签名,您可以像这样实现它:
public IEnumerable<Payment> Find(Expression<Func<Payment, bool>> where)
{
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))
};
if (where(payment)
{
this.payments.Add(payment);
}
}
return this.payments;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您的系统内存允许,您可以保留一个缓存列表(来自 GetAll())并在该列表上使用 Find()。根据列表的大小,这应该快一个数量级。