【发布时间】:2017-04-07 07:09:08
【问题描述】:
我们在应用程序中引入了一项新功能,该功能会影响数百个查询。我们必须设置一个bool 字段来指示许可证是否有效,以非常复杂的方式。
我想创建一个方法来返回这个bool 值,并且我想在每个查询中使用它。问题是,如果我按如下所示的方式使用它,它会对每个结果执行单独的查询。
如何使用Expression 将其编译为 SQL 并作为单个查询执行?
原始查询,需要改进
IQueryable<DeviceMinimal> devices =
from device in db.Devices
where device.AccountId = accountId
select new DeviceMinimal
{
Id = device.Id,
Name = device.Name,
LicenseIsValid = !checkForLicense ||
device.License != null && (
!device.License.TrialStarted
// && 12+ licensing rules
)
};
checkForLicense 是一个bool,表示不需要检查许可证。在某些情况下使用,需要考虑。
解决问题的代码,但会为每个设备引发单独的查询
IQueryable<DeviceMinimal> devices =
from device in db.Devices
where device.AccountId = accountId
select new DeviceMinimal
{
Id = device.Id,
Name = device.Name,
LicenseIsValid =
LicenseHelper.IsLicenseValid(checkForLicense).Invoke(device)
};
上面查询中使用的方法:
public static Func<Device, bool> IsLicenseEnabledAndValid(bool checkForLicense)
{
return result => !checkForLicense ||
result.License != null && (
!result.License.TrialStarted
// && 12+ licensing rules
);
}
【问题讨论】:
标签: c# linq linq-to-sql