嘿我有这样的代码它从读者返回模型列表。我怎样才能做得更好?不要使用这个address.Add(new Address { ID = (int) reader["ID"], Address = reader["Address"].ToString(), PhoneNumber = (int) reader["PhoneNumber"]});但使用更多这样的address.Add(new Address(reader?or somthing else));,或者也许如果我可以不使用列表并返回数据,仅在它返回的类中我可以添加到可观察集合? public async Task<IEnumerable<Address>> LoadDetail(int id) { await conn.OpenAsync(); List<Address> address = new List<Address>(); using (SqlCommand command = conn.CreateCommand()) { command.CommandText = $"SELECT * FROM Address WHERE ID = {id}";, using (SqlDataReader reader = command.ExecuteReader()) { while (await reader.ReadAsync()) { address.Add(new Address { ID = (int)reader["ID"], Address = reader["Address"].ToString(), PhoneNumber = (int)reader["PhoneNumber"] }); } } } return address; }
1 回答
LEATH
TA贡献1936条经验 获得超6个赞
如果不需要异步代码,您可以避免创建列表并编写以下内容:
while (reader.Read())
{
yield return new Address { ID = (int)reader["ID"], Address = reader["Address"].ToString(), PhoneNumber = (int)reader["PhoneNumber"] };
}
您可以通过读者的扩展方法来改进它:
yield return reader.GetAddress();
public static class ReaderExtensions
{
public static Address GetAddress(this SqlDataReader reader)
{
return new Address { ID = (int)reader["ID"], Address = reader["Address"].ToString(), PhoneNumber = (int)reader["PhoneNumber"] };
{
}
- 1 回答
- 0 关注
- 90 浏览
添加回答
举报
0/150
提交
取消