miércoles, 20 de enero de 2016

C# - retorno de DataSet desde consulta al Entity Framework / Convertir lista a DataTable

  public DataSet SelectbyPeriodoExcel(int periodo, ref string msj)
        {
            var ds = new DataSet();
            DataTable dt = new DataTable();
            try
            {
                using (var context = new leaOperModel())
                {
                    var dtContex = context.t_c13.Where(p => p.periodo == periodo).ToList();
                    // obj.AddRange(dtContex.Select(C13Be.DbToBe));
                    dt = ConvertToDataTable(dtContex);
                    ds.Tables.Add(dt);
                }
            }
            catch (Exception ex)
            {
                msj = ex.Message;
            }
            return ds;
            //return obj.ToList();
        }



 public DataTable ConvertToDataTable<T>(IList<T> data)
        {
            PropertyDescriptorCollection properties =
               TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            foreach (PropertyDescriptor prop in properties)
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
            foreach (T item in data)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }
            return table;

        }

No hay comentarios:

Publicar un comentario