我正试图从SQL Server数据库表中创建字符串列表。
这是我的存储过程:
ALTER PROCEDURE [dbo].[spCountry_GetCountryDataById]
@CountryId int
AS
BEGIN
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT
CountryName, Continent, Population, Capital,
Language, Religion, Currency, DishName
FROM
Country
WHERE
id = @CountryId
END
这是我的查询方法:
public static List<string> GetCountryDataByCountryId(int countryId)
{
List<string> countryData = new List<string>();
using (IDbConnection connection = new SqlConnection(CnnString("MathemaKids")))
{
DynamicParameters p = new DynamicParameters();
p.Add("CountryId", countryId);
countryData = connection.Query<string>("spCountry_GetCountryDataById", p, commandType: CommandType.StoredProcedure).ToList();
}
return countryData;
}
所以,我期望列表中有8个字符串,但当我运行它时,它只返回第一个字符串(CountryName
(。
问题出在哪里了,有人吗?
创建一个与表结构相对应的类-映射。试试,比如:
public class Country
{
//I have defined all as strings, better to define them corresponding to your table datatypes
public string CountryName {get;set;}
public string Continent {get;set;}
public string Population {get;set;}
public string Capital {get;set;}
public string Language {get;set;}
public string Religion {get;set;}
public string Currency {get;set;}
public string DishName {get;set;}
}
public static List<Country> GetCountryDataByCountryId(int countryId)
{
List<Country> countryData = new List<Country>();
using (IDbConnection connection = new SqlConnection(CnnString("MathemaKids")))
{
DynamicParameters p = new DynamicParameters();
p.Add("CountryId", countryId);
countryData = connection.Query<string>("spCountry_GetCountryDataById", p, commandType: CommandType.StoredProcedure).ToList();
}
return countryData;
}