如何从 SQL 查询中获取“带有数据的模型”列表?

嘿我有这样的代码


它从读者返回模型列表。我怎样才能做得更好?不要使用这个


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;

    }


智慧大石
浏览 91回答 1
1回答

LEATH

如果不需要异步代码,您可以避免创建列表并编写以下内容:while (reader.Read()){&nbsp; &nbsp; yield return new Address { ID = (int)reader["ID"], Address = reader["Address"].ToString(), PhoneNumber = (int)reader["PhoneNumber"] };}您可以通过读者的扩展方法来改进它:yield return reader.GetAddress();public static class ReaderExtensions{&nbsp; &nbsp; public static Address GetAddress(this SqlDataReader reader)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return new Address { ID = (int)reader["ID"], Address = reader["Address"].ToString(), PhoneNumber = (int)reader["PhoneNumber"] };&nbsp; &nbsp; {}
打开App,查看更多内容
随时随地看视频慕课网APP