[英]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).我正在尝试从多个表中检索数据并为每个查询结果创建一个类型化对象(类)(我可以使用Dapper引用)。
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.对于第一个查询,我需要获取country表的所有列和person表中的一个列。 Should I get Person object or can I get a typed object ?我应该得到Person 对象还是可以得到一个类型化的对象?
Thank you in advance!先感谢您!
You shouldn't return a Person
object because none of your queries return a Person
.您不应该返回Person
对象,因为您的查询都没有返回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 };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.