簡體   English   中英

如何從多個表中收集數據並創建類型化對象

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

我正在嘗試從多個表中檢索數據並為每個查詢結果創建一個類型化對象(類)(我可以使用Dapper引用)。

請在下面找到我的示例:

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

對於第一個查詢,我需要獲取country表的所有列和person表中的一個列。 我應該得到Person 對象還是可以得到一個類型化的對象

先感謝您!

您不應該返回Person對象,因為您的查詢都沒有返回Person 如果要返回類型化對象,則需要定義類型; 例如對於您的第一個查詢:

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

然后在您的第一個選擇中:

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

暫無
暫無

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

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