簡體   English   中英

C#:如何從表中獲取嵌套數據?

[英]C#: How do I get a nested data from table?

我是 C# 的新手,我遇到了下一個棘手的問題:

三個 JSON 文件用於播種三個 data.tables。 為了便於理解,我將我的數據稱為汽車,並使用表ManufacturersCarTypeCarModel

所以,我們假設有 3 個表:

第一個是主表( CarModel )。 有像這樣的列: Id, Name, MaxSpeed, ... id_of_manufacturer, id_of_car_type

Example of data:
['1', 'E34', '250', ... , '1', '1'] //BMW -> Sedan
['2', 'X6', '220', ... , '1', '2']  //BMW -> SUV
['3', 'Q7', '240', ... , '2', '2']  //Audi -> SUV

第二張表CarType ,行和下一列基本不變: Id, Type, ...

Example of data
[1, "Sedan", ...]
[2, "SUV", ...]

第 3制造商,行和下一列基本不變: Id, Company, ...

Example of data
[1, "BMW", ...]
[2, "AUDI", ...]

所以表之間的關系是這樣的:有一個CarModel,“E34”,在同一個表中引用CarType(id_of_car_type)“Sedan”和Manufacturer(id_of_manufacturer)“BMW”。

我的問題是,如何向數據庫發出請求,以便響應將包含 CarModel 表中的所有數據,其中的數據將如下所示?

1, BMW, ...
    1, Sedan, ...
        1, E34, 250, ...
    2, SUV, ...
        2, X6, 220, ...
2, Audi, ...
    2, SUV, ...
        3, Q7, 240, ...

目前我的解決方案是這樣的,但我認為它至少有性能問題......

namespace Cars.Data;

public class CarsRepository : ICarsRepository {
    private readonly DataContext _context;
    private readonly IMapper _mapper;
    public CarsRepository(DataContext context, IMapper mapper) {
        _mapper = mapper;
        _context = context;
    }

    public async Task<ICollection<CarTypes>> GetCarTypesForManufacturer(int id)
    {
        var carTypes = await _context.CarModels
            .Where(r => r.ManufacturerId == id)
            .Select(s => new {s.CarTypeId})
            .Distinct()
            .Select(s => s.CarTypeId)
            .ToListAsync();
        
        return await _context.CarTypes.Where(p => carTypes.Contains(p.Id)).ToListAsync();
    }

    public async Task<ICollection<Cars>> GetAllCars() {
        ICollection<Cars> result = new Collection<Cars>();
        var manufacturers = await _context.CarManufacturers.ToListAsync();
        foreach (var manufacturer in manufacturers) {
            var carTypes = await GetCarTypesForManufacturer(manufacturer.Id);
            ICollection<CarTypesWithCarModels> temp = new Collection<CarTypesWithCarModels>();
            foreach (var carType in carTypes) {
                var carModels = await _context.CarModels
                    .Where(r => r.ManufacturerId == manufacturer.Id && r.CarTypeId == carType.Id)
                    .ToListAsync();

                temp.Add(new CarTypesWithCarModels {
                    Id = carType.Id,
                    Name = carType.Name,
                    CarModels = carModels
                });
            }
            result.Add(new Cars {
                Id = manufacturer.Id,
                Name = manufacturer.Name,
                CarTypes = temp
            });
        }
        return result;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM