1
其實我也該樹方法在我的應用程序:包封物LINQ查詢不同的儲存庫,以避免重複的代碼
public decimal GetPayrunAllowanceYTDValue(Guid employeeId, Guid payrunId, Guid payItemId, DateTime paymentDate)
{
var payrunPayItem = _firstRepository.FilterBy(x => x.EmployeeId == employeeId
&& x.PayrunsId != payrunId
&& x.PayItemId == payItemId
&& x.EffectiveDate <= paymentDate, null)
.OrderByDescending(x => x.EffectiveDate).FirstOrDefault();
return payrunPayItem.YTD ?? 0;
}
public decimal GetPayrunDeductionsAndSupersYTDValue(Guid employeeId, Guid payrunId, Guid payItemId, DateTime paymentDate)
{
var payrunPayItem = _secondRepository.FilterBy(x => x.EmployeeId == employeeId
&& x.PayrunsId != payrunId
&& x.PayItemId == payItemId
&& x.EffectiveDate <= paymentDate, null)
.OrderByDescending(x => x.EffectiveDate).FirstOrDefault();
return payrunPayItem.YTD ?? 0;
}
public decimal GetPayrunCompanyContributionYTDValue(Guid employeeId, Guid payrunId, Guid payItemId, DateTime paymentDate)
{
var payrunPayItem = _thirdRepository.FilterBy(x => x.EmployeeId == employeeId
&& x.PayrunsId != payrunId
&& x.PayItemId == payItemId
&& x.EffectiveDate <= paymentDate, null)
.OrderByDescending(x => x.EffectiveDate).FirstOrDefault();
return payrunPayItem.YTD ?? 0;
}
正如你可以看到,這三個函數正好與一個區別是相同的,他們查詢到不同的存儲庫。我試圖重構這對一些通用的功能,像這樣的:
public decimal GetYtdValue<T>(T repository, Guid employeeId, Guid payrunId, Guid payItemId)
where T : IReadonlyRepository<FirstRepositoryType>, IReadonlyRepository<SecondRepositoryType>, IReadonlyRepository<ThirdRepositoryType>
{
var payrunPayItem = repository.FilterBy(x => x.EmployeeId == employeeId
&& x.PayrunsId != payrunId
&& x.PayItemId == payItemId, null).OrderByDescending(x => x.EffectiveDate).FirstOrDefault();
return (payrunPayItem.YTD ?? 0);
}
這裏的問題是因爲有一個「明確的引用」我發現了一個錯誤,因爲所有的庫具有相同的基本與那些屬性類。
所以,有一種方法可以重構這個,並有一個更優雅,而不是重複的代碼?
在此先感謝
我不能這樣做,因爲最後一個屬性是在每個單獨的存儲庫類(在最後一行payrunPayItem.YTD)。所以,我無法查詢基類的存儲庫,因爲我會錯過這個屬性。同時,我試圖通過一個IReadOnlyRepository不僅是一個類型。 –
然後你可以使用一個接口。請參閱編輯。 –