泛型方法从数据库返回List <t> </t>

时间:2011-12-29 18:51:57

标签: c# sql linq object

假设我有一个模型:

public class Person
{
public int ID {get;set;}
public string Name {get;set;}
}

在数据库中有一个表:

person(integer ID, char Name)

在编译器时间模型(Person)未知时,如何从数据库返回IEnumerable(或List)。例如,我认为,select方法必须具有以下结构:

public List<object> Select(string query, Dictionary<string, object> parameters)
        {
            List<object> listValue = new List<object>();
            using (var command = new MySqlCommand(query, connection))
            {
                #region fill command.Parameters.AddWithValue
                if (parameters != null)
                {
                    foreach (var param in parameters)
                    {
                        if (param.Value == null)
                        {
                            command.Parameters.AddWithValue("@" + param.Key, DBNull.Value);
                            continue;
                        }
                        DateTime _date = new DateTime();
                        if (DateTime.TryParse(param.Value.ToString(), out _date))
                        {
                            command.Parameters.AddWithValue("@" + param.Key, _date.ToString("yyyy-MM-dd"));
                            continue;
                        }
                        command.Parameters.AddWithValue("@" + param.Key, param.Value);
                    }
                }
                #endregion

                if (connection.State == System.Data.ConnectionState.Closed) connection.Open();
                try
                {
                    using (MySqlDataReader reader = command.ExecuteReader(System.Data.CommandBehavior.CloseConnection))
                    {
                        while (reader.Read())
                        {
                            object newObject = new object();

                           // What must I do there?

                            listValue.Add(new { });
                        }
                    }
                }
                catch (Exception ex) { }
                finally
                {
                    if (connection.State == System.Data.ConnectionState.Open)
                        connection.Close();
                }
            }
            return listValue;
}

1 个答案:

答案 0 :(得分:0)

我认为你需要一个像'Func'这样的新参数来让调用者决定如何将数据流从数据库转换为实体