I have created a join
with LINQ, and I'm wondering if there's a better way to accomplish it.
public async Task<IEnumerable<Prices>> GetTicketsPrices(db501Context _context,string Provider)
{
int ProviderKey = 0;
switch (Provider)
{
case "A":
ProviderKey = 1;
break;
case "B":
ProviderKey = 2;
break;
default:
ProviderKey = 0;
break;
}
var voucherPrices = await _context.VoucherPrices.Select(r => r).ToListAsync();
var Providers = await _context.VoucherProviders.Select(p => p).ToListAsync();
var voucherTypes = await _context.VoucherTypes.Select(t => t).ToListAsync();
var passengerType = await _context.VouchersPassengerTypes.Select(pt => pt).ToListAsync();
var newQueryObjectResult = from price in voucherPrices
join provider in Providers on price.Provider equals provider.Id
join type in voucherTypes on price.Type equals type.Id
join passenger in passengerType on price.PassengerType equals passenger.Id
where provider.Id == ProviderKey
select new Prices { Provider = provider.Name, PassengerType = passenger.Description,Type = type.Description,Price = price.Price};
return newQueryObjectResult;
}
Currently, I'm getting data from the context
four times. Each model's list result is assigned to a different variable.
Is this the best way of doing that? Can I use the context only one time in order to retrieve all the data besides using a stored procedure?
You could try something like this instead:
var prices = await (
from price in _context.VoucherPrices
where provider.Id == ProviderKey
select new Prices
{
Provider = price.Provider.Name,
PassengerType = price.PassengerType.Description,
Type = price.Type.Description,
Price = price.Price
}
).ToListAsync();
This is just using the navigation properties instead of manual joins. You would just need to be careful that there were records tied to the foreign keys (or do null
checks instead), like:
Provider = price.Provider != default ? price.Provider.Name : default,
PassengerType = price.PassengerType != default ? price.PassengerType.Description : default,
Type = price.Type != default ? price.Type.Description : default
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.