我的Property和PropertyCompliance实体看起来像这样......
public class Property{
public virtual ICollection<PropertyCompliance> ComplianceRecords {get;set;}
}
public class PropertyCompliance{
public virtual Property {get;set;}
public DateTime ComplianceDate {get;set;}
public ComplianceRating ComplianceValue {get;set;} //just an enum
}
在很多地方,我需要找到最接近特定日期的PropertyCompliance行。
var complianceRating = property.ComplianceRecords.OrderBy(cr=>cr.Date)
.Where(cr=>cr.ComplianceDate< checkDate).FirstOrDefault();
我知道我可以使用表达式来过滤ComplianceRecords:
var complianceRating = property.ComplianceRecords.Where(SomeExpression)
.OrderBy(cr=>cr.ComplianceDate).FirstOrDefault()
然而,这并没有真正减少重复的数量,因为它所做的只是替换Where()语句。
有没有办法将表达式应用于Property以允许此过滤在另一个表达式中发生?类似的东西:
private static Expression<Func<Property, ComplianceRating>> PropertyComplianceForDate(DateTime checkDate)
{
return p => p.ComplianceRatings
.OrderByDescending(cr => cr.Date)
.First(cr => cr.Date <= checkDate).ComplianceRating;
}
public Expression<Func<Property, bool>> PropertyIsCompliant(DateTime checkDate)
{
return (p) => PropertyComplianceForDate(checkDate) == ComplianceRating.Compliant;
}
使用&#34; PropertyComplianceForDate&#34;是一个可以转换为SQL的表达式,允许在SQL中使用PropertyIsCompliant表达式。
答案 0 :(得分:1)
您可以在类级别声明一个表达式并重用它。
或者,您可以在表格或扩展方法上创建方法。扩展方法(在静态类中)看起来像:
public static PropertyCompliance PropertyIsCompliant(this IEnumerable<PropertyCompliance> complianceRecords, DateTime checkDate) {
return complianceRatings
.OrderByDescending(cr => cr.Date)
.First(cr => cr.Date <= checkDate);
}