我正在使用 Xamarin 构建汽车管理应用程序,我的后端是 ASP.NET Web API。我有一个大型汽车数据集,可以按品牌、名称、年份、里程表和发动机容量找到汽车的价格。我尝试对大部分值进行平均,以便可以找到数据,但很多时候它不会返回任何内容。因此,我决定尝试多次查询数据库,但每次它不返回任何内容,我要么将一个值转换为一个区间(例如,里程表 = 100000,然后里程表 >= 80000 && 里程表 <= 120000)。它有点像这样,但我认为这不是正确的编写方式。我正在考虑策略模式,但不知道如何应用于我的案例。
我尝试过的是在存储库中获取汽车对象,然后我有六个方法只查询数据库,每个方法逐渐使用更少的参数。有很多 If Else。
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,则无法正常工作等等。 但我想问是否有办法让这段代码变得更好。
谢谢。
最佳答案
不要每次都尝试查找一辆汽车,而是让查询返回与制造
、型号
、年份
和CC
(因为这似乎是通用标准)并按里程表值对结果进行排序。然后,您的应用可以浏览列表(使用本地 LINQ 查询)以查找列表中的最佳匹配项。
由于所有网络流量,尝试多次查询单个匹配项将会变得太慢。
关于c# - 如果第一次没有找到任何内容,如何正确地多次查询数据库以获取某个值 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56393098/