简体   繁体   中英

How to collect data from multiple tables and create a typed object

I'm trying to retrieve data from multiple tables and create a typed objects (Class) for each query result (I can use Dapper reference).

Please find below my example:

List<ClassA> country = query<ClassA>(@"SELECT p.name, co.name, co.capital, co.area, co.population
                                       FROM t_person p
                                       INNER JOIN t_city c ON p.city_id = c.city_id
                                       INNER JOIN t_country co ON c.country_id = co.country_id");

List<ClassB> city = query<ClassB>(@"SELECT p.name, c.name
                                    FROM t_person p
                                    INNER JOIN t_city c ON p.city_id = c.city_i");

public class Person
{
    public int PersonId { get; set; }
    public string PersonName { get; set; }
    public City City { get; set; }
}

public class City
{
    public int CityId { get; set; }
    public string CityName { get; set; }
    public Country Country { get; set; }
}

public class Country
{
    public int CountryId { get; set; }
    public string CountryName { get; set; }
    public string CountryCapital { get; set; }
    public decimal CountryArea { get; set; }
    public decimal CountryPopulation { get; set; }
}

For the first query, I need get all columns of country table and only one column from person table. Should I get Person object or can I get a typed object ?

Thank you in advance!

You shouldn't return a Person object because none of your queries return a Person . If you want to return a typed object you need to define a type; for example for your first query:

public class PersonCountryResponse
{
    public string Person { get; init; }
    public string Country { get; init; }
    public string Capital { get; init; }
    public decimal Area { get; init; }
    public decimal Population { get; init; }
}

Then in your first select:

var pcrs = something.query(@"SELECT p.name AS personName, co.name AS countryName, co.capital, co.area, co.population
   FROM t_person p
   INNER JOIN t_city c ON p.city_id = c.city_id
   INNER JOIN t_country co ON c.country_id = co.country_id")
.Select(q => new PersonCountryResponse { Person = q.personName, Country = q.countryName, Capital = q.capital, Area = q.area, Population = q.population };

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