我有一个搜索功能,其中包含7个参数,其中6个是复选框值。它们是如下所示的bool。我的日期时间搜索有问题。如果用户检查该框是否要运行serach函数,其中数据库中的日期不为null。我的代码目前看起来像这样。但我想得到一些反馈,以了解如何改进我的代码以获得更好的性能和代码结构。
public List<Invoice> GetAllInvoicesBySearch(int merchant, long buyer, bool send, bool paid, bool firstReminder, bool secondReminder, bool invoiceClaim)
{
var sendValue = new InvoiceStatus();
var paidValue = new InvoiceStatus();
var firstRemind = new DateTime();
var secondRemind = new DateTime();
if (buyer <= 0)
{
return null;
}
if (send)
{
sendValue = InvoiceStatus.Sent;
}
if (paid)
{
paidValue = InvoiceStatus.Paid;
}
if (firstReminder)
{
firstRemind = DateTime.Now;
}
if (secondReminder)
{
secondRemind = DateTime.Now;
}
return
Context.Invoices.Where(
i =>
i.InstallationId == merchant && i.Buyer.Msisdn == buyer || i.Status == sendValue || i.Status == paidValue ||
i.FirstReminderDate == firstRemind || i.SecondReminderDate == secondRemind).ToList();
}
所以我的问题是目前正确的日期时间才能正确。关于如何解决我的问题并改进我的代码的任何建议?
答案 0 :(得分:0)
最好使用PredicateBuilder并转换为这样的扩展方法:
public static class ExtensionMethods {
public static IQueryable<Invoice> Search(this IQueryable<Invoice> src, int merchant,
long buyer, bool send, bool paid, bool firstReminder,
bool secondReminder, bool invoiceClaim)
{
var predicate = PredicateBuilder.False<Invoice>();
var sendValue = new InvoiceStatus();
var paidValue = new InvoiceStatus();
var firstRemind = new DateTime();
var secondRemind = new DateTime();
if (buyer <= 0)
{
return src.Where(predicate);
}
predicate=predicate.Or(i=>i.InstallationId == merchant && i.Buyer.Msisdn == buyer);
if (send)
{
predicate=predicate.Or(i=>i.Status == InvoiceStatus.Sent);
}
if (paid)
{
predicate=predicate.Or(i=>i.Status == InvoiceStatus.Paid);
}
if (firstReminder)
{
predicate=predicate.Or(i=>i.FirstReminderDate == DateTime.Today);
}
if (secondReminder)
{
predicate=predicate.Or(i=>i.SecondReminderDate == DateTime.Today);
}
return src.Where(predicate);
}
}
此外,如果我正确理解您的代码,InvoiceStatus应该是枚举,或者至少InvoiceStatus.Sent和InvoiceStatus.Paid应该被标记为静态。像这样引用它:
Context.Invoices.Search(...).OrderBy(...)...
如果您需要在原始搜索之外进行排序,分页和过滤,这将使得进一步操作变得更加容易。