繁体   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