[英]How can I properly query a database multiple times for a value if the first time it didn't find anything C#
我正在使用Xamarin构建汽车管理应用程序,而我的后端是一个ASP.NET Web API。 我有一个大型汽车数据集,我可以通过Make,Name,Year,Odometer和Engine Capacity查找汽车的价格。 我试图平均大部分值,以便我可以找到数据,但很多时候它只是没有返回任何东西。 所以我决定尝试多次查询数据库,但每次都没有返回任何内容,我要么将值转换为间隔(例如,里程表= 100000,然后里程表> = 80000 &&里程表<= 120000)。 它有点像这样,但我不认为这是写它的正确方法。 我在考虑策略模式,但无法弄清楚如何在我的情况下应用。
我试过的是在我得到汽车对象的地方创建Repository,然后我有六个方法只查询数据库,每个方法逐渐用更少的参数。 还有很多If Elses。
public GetCarPriceResponse GetPrice(GetCarPriceRequest car)
{
var price = new GetCarPriceResponse
{
Errors = new List<string>()
};
if (GetPriceFirst(car) == null)
if (GetPriceSecond(car) == null)
if (GetPriceThird(car) == null)
if (GetPriceFourth(car) == null)
if (GetPriceFifth(car) == null)
if (GetPriceSixth(car) == null)
{
price.Success = false;
price.Errors.Add("Could not find car
price");
}
else
{
price = GetPriceSixth(car);
}
else price = GetPriceFifth(car);
else price = GetPriceFourth(car);
else price = GetPriceThird(car);
else price = GetPriceSecond(car);
else price = GetPriceFirst(car);
price.Success = true;
return price;
}
第一个函数如下所示:
public GetCarPriceResponse GetPriceFirst(GetCarPriceRequest car)
{
var prices = _context.CarPrices.Where(p =>
p.make == car.make &&
p.model == car.model &&
p.year == car.year &&
p.CC == car.CC &&
p.odometer == car.odometer).ToList();
if (prices.Count == 0) return null;
return CalculateAveragePrice(prices);
}
第三个是这样的:
public GetCarPriceResponse GetPriceThird(GetCarPriceRequest car)
{
var differenceDown = 0;
var differenceUp = 0;
if (car.odometer < 50000)
{
differenceDown = 0;
differenceUp = 50000;
}
else if (car.odometer > 50000)
{
differenceDown = 50000;
differenceUp = 50000;
}
else if (car.odometer > 215000)
{
differenceDown = 50000;
differenceUp = 0;
}
var prices = _context.CarPrices.Where(p =>
p.make == car.make &&
p.model == car.model &&
p.year == car.year &&
p.CC == car.CC &&
p.odometer >= car.odometer - differenceDown &&
p.odometer <= car.odometer + differenceUp).ToList();
if (prices.Count == 0) return null;
return CalculateAveragePrice(prices);
}
在第四个中我完全消除了里程表参数,在第六个中我查询了一个基于里程表,发动机容量和型号年份的平均价格的不同数据库。 这是第五种方法:
public GetCarPriceResponse GetPriceFifth(GetCarPriceRequest car)
{
var prices = _context.CarPrices.Where(p =>
p.make == car.make &&
p.model == car.model &&
p.year >= car.year - 2 &&
p.year <= car.year + 2 &&
p.CC == car.CC).ToList();
if (prices.Count == 0) return null;
return CalculateAveragePrice(prices);
}
它现在工作正常,但是例如如果你添加一辆电动汽车,发动机容量为0,它就不能正常运行等等。 但我想问是否有办法让这段代码变得更好。
谢谢。
每次查询返回一个匹配make
, model
, year
和CC
的汽车列表(因为这似乎是常用标准),而不是试图找到单个汽车,并按里程表值对结果进行排序。 然后,您的应用可以查看列表(使用本地LINQ查询)以查找列表中的最佳匹配。
由于所有网络流量,尝试多次查询单个匹配将变得太慢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.