【问题标题】:LINQ JOIN in .NET Core 3.1.NET Core 3.1 中的 LINQ JOIN
【发布时间】:2020-04-30 08:54:17
【问题描述】:

我用 LINQ 创建了一个join,我想知道是否有更好的方法来完成它。

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;
}

目前,我从context 获取数据四次。每个模型的列表结果都分配给不同的变量。

这是最好的方法吗?除了使用存储过程之外,我可以只使用一次上下文来检索所有数据吗?

【问题讨论】:

    标签: c# linq asp.net-core asp.net-core-3.1


    【解决方案1】:

    你可以试试这样的:

    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();
    

    这只是使用导航属性而不是手动连接。您只需要注意与外键相关的记录(或改为进行null 检查),例如:

    Provider = price.Provider != default ? price.Provider.Name : default,
    PassengerType = price.PassengerType != default ? price.PassengerType.Description : default,
    Type = price.Type != default ? price.Type.Description : default
    

    【讨论】:

    • 完美!就像导航的魅力一样。
    猜你喜欢
    • 2021-08-30
    • 1970-01-01
    • 2022-01-09
    • 2021-03-16
    • 2021-01-24
    • 2021-11-25
    • 2020-06-18
    • 2020-05-17
    • 1970-01-01
    相关资源
    最近更新 更多