我正在嘗試從多個表中檢索資料并為每個查詢結果創建一個型別化物件(類)(我可以使用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 物件還是可以得到一個型別化的物件?
先感謝您!
uj5u.com熱心網友回復:
你不應該回傳一個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 };
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/478957.html
