简体   繁体   中英

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

I'm newbie in C# and I faced a next tricky problem:

There are three JSON files for seeding three data.tables. To keep it simple for understanding I will refer to my data as cars with the tables Manufacturers , CarType , CarModel .

So, let's assume there are 3 tables:

1st is the Main Table ( CarModel ). There are columns like: 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

2nd Table CarType with the mostly constant rows and next columns: Id, Type, ...

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

3rd Table Manufacturers with the mostly constant rows and next columns: Id, Company, ...

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

So the relations between tables are like this: There is a CarModel, "E34", that in the same table reffers to CarType (id_of_car_type) "Sedan" and Manufacturer (id_of_manufacturer) "BMW".

My Question is, how to make a request to the database, so the response will have all data from CarModel table and data in it will look like this?

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

Currently my solution is like this, but I think that it has a performance issues at least...

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM