[英]Mapping List<KeyValuePair<string,int>> to custom object in C#
我有一個返回List<KeyValuePair<string,int>>
。 這些是來自數據庫中不同表的列數據,具體取決於調用的參數,我想根據返回的表數據映射到自定義對象。
例如,返回列表包含來自表 1 的數據和列(C1, C2, C3, C4)
可能的返回值是
KeyValPair<C1, ValueOfC1>
KeyValPair<C2, ValueofC2>
etc....
此列表應映射到 CustomC1 列表,其中 CustomC1 定義如下:
public class CustumC1 { int c1, int c2, int c3, int c4 }
我需要轉換list
中的KeyValuePair
到List
的CustomC1
。
所以我目前有一個方法定義是
List<KeyValuePair<string,int>> MyMethod(int param)
而且我要
List<TResult> MyMethod<TResult> (int param)
下面是我的原始方法,需要更改以返回提供的對象:
private async Task<List<List<KeyValuePair<string, string>>>> GetData(SqlConnection conn)
{
List<string> columnNames = new List<string>();
string sql = CustomQueryString;
List<List<KeyValuePair<string, string>>> result = new List<List<KeyValuePair<string, string>>>();
var reader = await new SqlCommand(sql, conn).ExecuteReaderAsync();
for (int i = 0; i < reader.FieldCount; i++)
{
columnNames.Add(reader.GetName(i));
}
while (reader.Read())
{
List<KeyValuePair<string, string>> resultRecord = new List<KeyValuePair<string, string>>();
foreach (var columnName in columnNames)
{
resultRecord.Add(new KeyValuePair<string, string>(key: columnName, value: reader[columnName].ToString()));
}
result.Add(resultRecord);
}
return result;
}
任何幫助將不勝感激。
你用什么從數據庫中讀取? 以及如何映射到List<KeyValuePair<string,int>>
?據我所知,您正在映射到 keyValuePair 以便稍后將其映射到通用對象。 我認為這不是一個好方法,因為您將面臨更多的可擴展性和錯誤的復雜性。 最好有一個從數據庫返回一個具體對象的具體方法,正如評論中提到的使用 dapper 將是一個很好的解決方案。 否則你可以做這樣的事情:
var modelProperties = modelType.GetProperties();// modelType is your generic object type
var instance = Activator.CreateInstance(modelType);
foreach (var property in modelProperties)
{
var propertyInfo = instance.GetType().GetProperty(property.Name);
var propertyValue = yourList.FirstOrDefault(x=>x.Key==property.Name);
propertyInfo.SetValue(instance, ChangeType(propertyValue, propertyInfo.PropertyType), null);
}
更新
例如,這段代碼清晰而富有表現力,告訴我其他開發人員在做什么,我可以理解它的上下文,它使用 Dapper 進行查詢並按照 CQRS 原則制作:
public class GetHousesHandler : IRequestHandler<GetHouses, IEnumerable<House>>
{
private readonly IDbConnection _connection;
public GetHousesHandler(IDbConnection connection)
{
_connection = connection ?? throw new ArgumentNullException(nameof(connection));
}
public async Task<IEnumerable<House>> Handle(GetHouses request, CancellationToken cancellationToken)
{
var sql = $@"
SELECT StreetName AS {nameof(House.StreetName)}
, Number AS {nameof(House.Number)}
FROM dbo.HouseView
WHERE Number = @Number;";
var param = new
{
request.Number,
};
return await _connection.QueryAsync<House>(
sql: sql,
param: param
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.