Convert Datatable to strogly Typed Model - c#

I have a model class like this
public class Profile
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string NickName { get; set; }
public string City { get; set; }
public string State { get; set; }
...................... etc
}
And a datatable which is of same type of data. Means columns in datattable will be FirstName,LastName,NickName,City,State. And the data table will have only one row.
Now I want to copy the data in this datatable to Profile model. Right now I am doing like this.
var sp = new Profile();
DataTable dt = ProfileDAL.GetProfile(profileId);
if (profile.Rows.Count > 0)
{
sp.FirstName = ReferenceEquals(dt.Rows[0]["FirstName"], "")
? ""
: dt.Rows[0]["FirstName"].ToString();
sp.LastName = ReferenceEquals(dt.Rows[0]["LastName"], "")
? ""
: dt.Rows[0]["LastName"].ToString();
sp.NickName = ReferenceEquals(dt.Rows[0]["NickName"], "")
? ""
: dt.Rows[0]["NickName"].ToString();
}
is there any elegant way of doing this? Like I have a huge datatable to convert and when I do it like what I am doing now. It will take a long time and a number of lines of code. Can anyone point out anything better?

This what I used that saved me time. I created it as an extension to DataTable. All you have to do is
DataTable dt = ProfileDAL.GetProfile(profileId);
var profile = dt.Rows[0].ToEntity<Profile>(); //<-- new changes
And if you want a list
DataTable dt = ProfileDAL.GetProfiles();
var profiles = dt.ToList<Profile>();
Or get your entity with LINQ
DataTable dt = ProfileDAL.GetProfile(profileId);
var profile = dt.ToList<Profile>().FirstOrDefault();
The class
public static class DataExtensions
{
public static T ToEntity<T>(this DataRow dr) where T : new()
{
DataColumnCollection columns = dr.Table.Columns;
T obj1 = new T();
foreach (PropertyInfo propertyInfo in obj1.GetType().GetProperties())
{
if (columns.Contains(propertyInfo.Name) && dr[propertyInfo.Name] != DBNull.Value)
{
if (propertyInfo.PropertyType.IsGenericType)
{
object obj2 = Convert.ChangeType(dr[propertyInfo.Name], propertyInfo.PropertyType.GetGenericArguments()[0]);
propertyInfo.SetValue((object) obj1, obj2, (object[]) null);
}
else
{
object obj2 = Convert.ChangeType(dr[propertyInfo.Name], propertyInfo.PropertyType);
propertyInfo.SetValue((object) obj1, obj2, (object[]) null);
}
}
}
return obj1;
}
public static List<T> ToList<T>(this DataTable dt) where T : new()
{
List<T> list = new List<T>();
foreach (DataRow dr in (InternalDataCollectionBase) dt.Rows)
list.Add(DataExtensions.ToEntity<T>(dr));
return list;
}
}

here is solution i use this for map data table with entity
or you can use the AutoMapper
IList<Profile> result = new List<Profile>();
result = currentDataTable.AsEnumerable().Select(row => new Profile
{
FirstName = row["FirstName"].ToString(),
LastName = row["LastName"].ToString()
}
).ToList<Profile>();

Related

How to convert Datatable to class list c# [duplicate]

Currently, I'm using:
DataTable dt = CreateDataTableInSomeWay();
List<DataRow> list = new List<DataRow>();
foreach (DataRow dr in dt.Rows)
{
list.Add(dr);
}
Is there a better/magic way?
If you're using .NET 3.5, you can use DataTableExtensions.AsEnumerable (an extension method) and then if you really need a List<DataRow> instead of just IEnumerable<DataRow> you can call Enumerable.ToList:
IEnumerable<DataRow> sequence = dt.AsEnumerable();
or
using System.Linq;
...
List<DataRow> list = dt.AsEnumerable().ToList();
List<Employee> emp = new List<Employee>();
//Maintaining DataTable on ViewState
//For Demo only
DataTable dt = ViewState["CurrentEmp"] as DataTable;
//read data from DataTable
//using lamdaexpression
emp = (from DataRow row in dt.Rows
select new Employee
{
_FirstName = row["FirstName"].ToString(),
_LastName = row["Last_Name"].ToString()
}).ToList();
With C# 3.0 and System.Data.DataSetExtensions.dll,
List<DataRow> rows = table.Rows.Cast<DataRow>().ToList();
You could use
List<DataRow> list = new List<DataRow>(dt.Select());
dt.Select() will return all rows in your table, as an array of datarows, and the List constructor accepts that array of objects as an argument to initially fill your list with.
If you just want a list of values from the "ID" int field returned, you could use...
List<int> ids = (from row in dt.AsEnumerable() select Convert.ToInt32(row["ID"])).ToList();
You can create a extension function as :
public static List<T> ToListof<T>(this DataTable dt)
{
const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
var columnNames = dt.Columns.Cast<DataColumn>()
.Select(c => c.ColumnName)
.ToList();
var objectProperties = typeof(T).GetProperties(flags);
var targetList = dt.AsEnumerable().Select(dataRow =>
{
var instanceOfT = Activator.CreateInstance<T>();
foreach (var properties in objectProperties.Where(properties => columnNames.Contains(properties.Name) && dataRow[properties.Name] != DBNull.Value))
{
properties.SetValue(instanceOfT, dataRow[properties.Name], null);
}
return instanceOfT;
}).ToList();
return targetList;
}
var output = yourDataInstance.ToListof<targetModelType>();
I have added some modification to the code from this answer (https://stackoverflow.com/a/24588210/4489664) because for nullable Types it will return exception
public static List<T> DataTableToList<T>(this DataTable table) where T: new()
{
List<T> list = new List<T>();
var typeProperties = typeof(T).GetProperties().Select(propertyInfo => new
{
PropertyInfo = propertyInfo,
Type = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType
}).ToList();
foreach (var row in table.Rows.Cast<DataRow>())
{
T obj = new T();
foreach (var typeProperty in typeProperties)
{
object value = row[typeProperty.PropertyInfo.Name];
object safeValue = value == null || DBNull.Value.Equals(value)
? null
: Convert.ChangeType(value, typeProperty.Type);
typeProperty.PropertyInfo.SetValue(obj, safeValue, null);
}
list.Add(obj);
}
return list;
}
using System.Data;
var myEnumerable = myDataTable.AsEnumerable();
List<MyClass> myClassList =
(from item in myEnumerable
select new MyClass{
MyClassProperty1 = item.Field<string>("DataTableColumnName1"),
MyClassProperty2 = item.Field<string>("DataTableColumnName2")
}).ToList();
Again, using 3.5 you may do it like:
dt.Select().ToList()
BRGDS
// this is better suited for expensive object creation/initialization
IEnumerable<Employee> ParseEmployeeTable(DataTable dtEmployees)
{
var employees = new ConcurrentBag<Employee>();
Parallel.ForEach(dtEmployees.AsEnumerable(), (dr) =>
{
employees.Add(new Employee()
{
_FirstName = dr["FirstName"].ToString(),
_LastName = dr["Last_Name"].ToString()
});
});
return employees;
}
A more 'magic' way, and doesn't need .NET 3.5.
If, for example, DBDatatable was returning a single column of Guids (uniqueidentifier in SQL) then you could use:
Dim gList As New List(Of Guid)
gList.AddRange(DirectCast(DBDataTable.Select(), IEnumerable(Of Guid)))
DataTable dt; // datatable should contains datacolumns with Id,Name
List<Employee> employeeList=new List<Employee>(); // Employee should contain EmployeeId, EmployeeName as properties
foreach (DataRow dr in dt.Rows)
{
employeeList.Add(new Employee{EmployeeId=dr.Id,EmplooyeeName=dr.Name});
}
The Easiest way of Converting the DataTable into the Generic list of class
using Newtonsoft.Json;
var json = JsonConvert.SerializeObject(dataTable);
var model = JsonConvert.DeserializeObject<List<ClassName>>(json);
DataTable.Select() doesnt give the Rows in the order they were present in the datatable.
If order is important I feel iterating over the datarow collection and forming a List is the right way to go or you could also use overload of DataTable.Select(string filterexpression, string sort).
But this overload may not handle all the ordering (like order by case ...) that SQL provides.
/* This is a generic method that will convert any type of DataTable to a List
*
*
* Example : List< Student > studentDetails = new List< Student >();
* studentDetails = ConvertDataTable< Student >(dt);
*
* Warning : In this case the DataTable column's name and class property name
* should be the same otherwise this function will not work properly
*/
The following are the two functions in which if we pass a
DataTable
and a user defined class.
It will then return the List of that class with the DataTable data.
public static List<T> ConvertDataTable<T>(DataTable dt)
{
List<T> data = new List<T>();
foreach (DataRow row in dt.Rows)
{
T item = GetItem<T>(row);
data.Add(item);
}
return data;
}
private static T GetItem<T>(DataRow dr)
{
Type temp = typeof(T);
T obj = Activator.CreateInstance<T>();
foreach (DataColumn column in dr.Table.Columns)
{
foreach (PropertyInfo pro in temp.GetProperties())
{
//in case you have a enum/GUID datatype in your model
//We will check field's dataType, and convert the value in it.
if (pro.Name == column.ColumnName){
try
{
var convertedValue = GetValueByDataType(pro.PropertyType, dr[column.ColumnName]);
pro.SetValue(obj, convertedValue, null);
}
catch (Exception e)
{
//ex handle code
throw;
}
//pro.SetValue(obj, dr[column.ColumnName], null);
}
else
continue;
}
}
return obj;
}
This method will check the datatype of field, and convert dataTable value in to that datatype.
private static object GetValueByDataType(Type propertyType, object o)
{
if (o.ToString() == "null")
{
return null;
}
if (propertyType == (typeof(Guid)) || propertyType == typeof(Guid?))
{
return Guid.Parse(o.ToString());
}
else if (propertyType == typeof(int) || propertyType.IsEnum)
{
return Convert.ToInt32(o);
}
else if (propertyType == typeof(decimal) )
{
return Convert.ToDecimal(o);
}
else if (propertyType == typeof(long))
{
return Convert.ToInt64(o);
}
else if (propertyType == typeof(bool) || propertyType == typeof(bool?))
{
return Convert.ToBoolean(o);
}
else if (propertyType == typeof(DateTime) || propertyType == typeof(DateTime?))
{
return Convert.ToDateTime(o);
}
return o.ToString();
}
To call the preceding method, use the following syntax:
List< Student > studentDetails = new List< Student >();
studentDetails = ConvertDataTable< Student >(dt);
Change the Student class name and dt value based on your requirements. In this case the DataTable column's name and class property name should be the same otherwise this function will not work properly.
lPerson = dt.AsEnumerable().Select(s => new Person()
{
Name = s.Field<string>("Name"),
SurName = s.Field<string>("SurName"),
Age = s.Field<int>("Age"),
InsertDate = s.Field<DateTime>("InsertDate")
}).ToList();
Link to working DotNetFiddle Example
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Data.DataSetExtensions;
public static void Main()
{
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("SurName", typeof(string));
dt.Columns.Add("Age", typeof(int));
dt.Columns.Add("InsertDate", typeof(DateTime));
var row1= dt.NewRow();
row1["Name"] = "Adam";
row1["SurName"] = "Adam";
row1["Age"] = 20;
row1["InsertDate"] = new DateTime(2020, 1, 1);
dt.Rows.Add(row1);
var row2 = dt.NewRow();
row2["Name"] = "John";
row2["SurName"] = "Smith";
row2["Age"] = 25;
row2["InsertDate"] = new DateTime(2020, 3, 12);
dt.Rows.Add(row2);
var row3 = dt.NewRow();
row3["Name"] = "Jack";
row3["SurName"] = "Strong";
row3["Age"] = 32;
row3["InsertDate"] = new DateTime(2020, 5, 20);
dt.Rows.Add(row3);
List<Person> lPerson = new List<Person>();
lPerson = dt.AsEnumerable().Select(s => new Person()
{
Name = s.Field<string>("Name"),
SurName = s.Field<string>("SurName"),
Age = s.Field<int>("Age"),
InsertDate = s.Field<DateTime>("InsertDate")
}).ToList();
foreach(Person pers in lPerson)
{
Console.WriteLine("{0} {1} {2} {3}", pers.Name, pers.SurName, pers.Age, pers.InsertDate);
}
}
public class Person
{
public string Name { get; set; }
public string SurName { get; set; }
public int Age { get; set; }
public DateTime InsertDate { get; set; }
}
}
Use System.Data namespace then you will get .AsEnumerable().
This worked for me:
Need at least .Net Framework 3.5,
Code below displays DataRow turned to Generic.IEnumerable, comboBox1 has been used for a better illustration.
using System.Linq;
DataTable dt = new DataTable();
dt = myClass.myMethod();
List<object> list = (from row in dt.AsEnumerable() select (row["name"])).ToList();
comboBox1.DataSource = list;
Output
public class ModelUser
{
#region Model
private string _username;
private string _userpassword;
private string _useremail;
private int _userid;
/// <summary>
///
/// </summary>
public int userid
{
set { _userid = value; }
get { return _userid; }
}
/// <summary>
///
/// </summary>
public string username
{
set { _username = value; }
get { return _username; }
}
/// <summary>
///
/// </summary>
public string useremail
{
set { _useremail = value; }
get { return _useremail; }
}
/// <summary>
///
/// </summary>
public string userpassword
{
set { _userpassword = value; }
get { return _userpassword; }
}
#endregion Model
}
public List<ModelUser> DataTableToList(DataTable dt)
{
List<ModelUser> modelList = new List<ModelUser>();
int rowsCount = dt.Rows.Count;
if (rowsCount > 0)
{
ModelUser model;
for (int n = 0; n < rowsCount; n++)
{
model = new ModelUser();
model.userid = (int)dt.Rows[n]["userid"];
model.username = dt.Rows[n]["username"].ToString();
model.useremail = dt.Rows[n]["useremail"].ToString();
model.userpassword = dt.Rows[n]["userpassword"].ToString();
modelList.Add(model);
}
}
return modelList;
}
static DataTable GetTable()
{
// Here we create a DataTable with four columns.
DataTable table = new DataTable();
table.Columns.Add("userid", typeof(int));
table.Columns.Add("username", typeof(string));
table.Columns.Add("useremail", typeof(string));
table.Columns.Add("userpassword", typeof(string));
// Here we add five DataRows.
table.Rows.Add(25, "Jame", "Jame#hotmail.com", DateTime.Now.ToString());
table.Rows.Add(50, "luci", "luci#hotmail.com", DateTime.Now.ToString());
table.Rows.Add(10, "Andrey", "Andrey#hotmail.com", DateTime.Now.ToString());
table.Rows.Add(21, "Michael", "Michael#hotmail.com", DateTime.Now.ToString());
table.Rows.Add(100, "Steven", "Steven#hotmail.com", DateTime.Now.ToString());
return table;
}
protected void Page_Load(object sender, EventArgs e)
{
List<ModelUser> userList = new List<ModelUser>();
DataTable dt = GetTable();
userList = DataTableToList(dt);
gv.DataSource = userList;
gv.DataBind();
}[enter image description here][1]
</asp:GridView>
</div>
We can use a Generic Method for converting DataTable to List instead of manually converting a DataTable to List.
Note: DataTable's ColumnName and Type's PropertyName should be same.
Call the below Method:
long result = Utilities.ConvertTo<Student>(dt ,out listStudent);
// Generic Method
public class Utilities
{
public static long ConvertTo<T>(DataTable table, out List<T> entity)
{
long returnCode = -1;
entity = null;
if (table == null)
{
return -1;
}
try
{
entity = ConvertTo<T>(table.Rows);
returnCode = 0;
}
catch (Exception ex)
{
returnCode = 1000;
}
return returnCode;
}
static List<T> ConvertTo<T>(DataRowCollection rows)
{
List<T> list = null;
if (rows != null)
{
list = new List<T>();
foreach (DataRow row in rows)
{
T item = CreateItem<T>(row);
list.Add(item);
}
}
return list;
}
static T CreateItem<T>(DataRow row)
{
string str = string.Empty;
string strObj = string.Empty;
T obj = default(T);
if (row != null)
{
obj = Activator.CreateInstance<T>();
strObj = obj.ToString();
NameValueCollection objDictionary = new NameValueCollection();
foreach (DataColumn column in row.Table.Columns)
{
PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
if (prop != null)
{
str = column.ColumnName;
try
{
objDictionary.Add(str, row[str].ToString());
object value = row[column.ColumnName];
Type vType = obj.GetType();
if (value == DBNull.Value)
{
if (vType == typeof(int) || vType == typeof(Int16)
|| vType == typeof(Int32)
|| vType == typeof(Int64)
|| vType == typeof(decimal)
|| vType == typeof(float)
|| vType == typeof(double))
{
value = 0;
}
else if (vType == typeof(bool))
{
value = false;
}
else if (vType == typeof(DateTime))
{
value = DateTime.MaxValue;
}
else
{
value = null;
}
prop.SetValue(obj, value, null);
}
else
{
prop.SetValue(obj, value, null);
}
}
catch(Exception ex)
{
}
}
}
PropertyInfo ActionProp = obj.GetType().GetProperty("ActionTemplateValue");
if (ActionProp != null)
{
object ActionValue = objDictionary;
ActionProp.SetValue(obj, ActionValue, null);
}
}
return obj;
}
}
You can use a generic method like that for datatable to generic list
public static List<T> DataTableToList<T>(this DataTable table) where T : class, new()
{
try
{
List<T> list = new List<T>();
foreach (var row in table.AsEnumerable())
{
T obj = new T();
foreach (var prop in obj.GetType().GetProperties())
{
try
{
PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
if (propertyInfo.PropertyType.IsEnum)
{
propertyInfo.SetValue(obj, Enum.Parse(propertyInfo.PropertyType, row[prop.Name].ToString()));
}
else
{
propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
}
}
catch
{
continue;
}
}
list.Add(obj);
}
return list;
}
catch
{
return null;
}
}
Converting DataTable to Generic Dictionary
public static Dictionary<object,IList<dynamic>> DataTable2Dictionary(DataTable dt)
{
Dictionary<object, IList<dynamic>> dict = new Dictionary<dynamic, IList<dynamic>>();
foreach(DataColumn column in dt.Columns)
{
IList<dynamic> ts = dt.AsEnumerable()
.Select(r => r.Field<dynamic>(column.ToString()))
.ToList();
dict.Add(column, ts);
}
return dict;
}
Use Extension :
public static class Extensions
{
#region Convert Datatable To List
public static IList<T> ToList<T>(this DataTable table) where T : new()
{
IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
IList<T> result = new List<T>();
foreach (var row in table.Rows)
{
var item = CreateItemFromRow<T>((DataRow)row, properties);
result.Add(item);
}
return result;
}
private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
{
T item = new T();
foreach (var property in properties)
{
property.SetValue(item, row[property.Name], null);
}
return item;
}
#endregion
}
To assign the DataTable rows to the generic List of class
List<Candidate> temp = new List<Candidate>();//List that holds the Candidate Class,
//Note:The Candidate class contains RollNo,Name and Department
//tb is DataTable
temp = (from DataRow dr in tb.Rows
select new Candidate()
{
RollNO = Convert.ToInt32(dr["RollNO"]),
Name = dr["Name"].ToString(),
Department = dr["Department"].ToString(),
}).ToList();
you can use following two Generic functions
private static List<T> ConvertDataTable<T>(DataTable dt)
{
List<T> data = new List<T>();
foreach (DataRow row in dt.Rows)
{
T item = GetItem<T>(row);
data.Add(item);
}
return data;
}
private static T GetItem<T>(DataRow dr)
{
Type temp = typeof(T);
T obj = Activator.CreateInstance<T>();
foreach (DataColumn column in dr.Table.Columns)
{
foreach (PropertyInfo pro in temp.GetProperties())
{
if (pro.Name == column.ColumnName)
pro.SetValue(obj, dr[column.ColumnName].ToString(), null);
else
continue;
}
}
return obj;
}
and use it as following
List<StudentScanExamsDTO> studentDetails = ConvertDataTable<StudentScanExamsDTO>(dt);
If anyone want's to create custom function to convert datatable to list
class Program
{
static void Main(string[] args)
{
DataTable table = GetDataTable();
var sw = new Stopwatch();
sw.Start();
LinqMethod(table);
sw.Stop();
Console.WriteLine("Elapsed time for Linq Method={0}", sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();
ForEachMethod(table);
sw.Stop();
Console.WriteLine("Elapsed time for Foreach method={0}", sw.ElapsedMilliseconds);
Console.ReadKey();
}
private static DataTable GetDataTable()
{
var table = new DataTable();
table.Columns.Add("ID", typeof(double));
table.Columns.Add("CategoryName", typeof(string));
table.Columns.Add("Active", typeof(double));
var rand = new Random();
for (int i = 0; i < 100000; i++)
{
table.Rows.Add(i, "name" + i, rand.Next(0, 2));
}
return table;
}
private static void LinqMethod(DataTable table)
{
var list = table.AsEnumerable()
.Skip(1)
.Select(dr =>
new Category
{
Id = Convert.ToInt32(dr.Field<double>("ID")),
CategoryName = dr.Field<string>("CategoryName"),
IsActive =
dr.Field<double>("Active") == 1 ? true : false
}).ToList();
}
private static void ForEachMethod(DataTable table)
{
var categoryList = new List<Category>(table.Rows.Count);
foreach (DataRow row in table.Rows)
{
var values = row.ItemArray;
var category = new Category()
{
Id = Convert.ToInt32(values[0]),
CategoryName = Convert.ToString(values[1]),
IsActive = (double)values[2] == 1 ? true : false
};
categoryList.Add(category);
}
}
private class Category
{
public int Id { get; set; }
public string CategoryName { get; set; }
public bool IsActive { get; set; }
}
}
If we execute above code, Foreach method finishes in 56ms while linq one takes 101ms ( for 1000 records).
So Foreach method is better to use.
Source:Ways to Convert Datatable to List in C# (with performance test example)
try this using Newtonsoft Json:
var json = JsonConvert.SerializeObject(dataTable);
var YourConvertedDataType = JsonConvert.DeserializeObject<YourDataType>(json);
To get List of values instead of ItemArray, do this:
List<string> s = dt.AsEnumerable().Select(x => x[0].ToString()).ToList();
The above assumes that you want list of string values from column 0.

A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'

The below code will read oracle table and return json result, to the view.
The data are loaded successfully into the datalist, however the view is throwing the below error:
A circular reference was detected while serializing
an object of type 'System.Reflection.RuntimeModule'.
Q1: What I can do to fix the error? I already have a model defined for the data I need to retrieve (see the below model definition)
Q2: Is the above method is the best practice to read a database and return json?
public JsonResult StudList()
{
string SQL = "select id, name, div_code, block, from students where ....."; //see the below model
var con = DB.GetConnection();
con.Open();
OracleDataAdapter oraAdapt = new OracleDataAdapter(SQL, con);
DataTable dt = new DataTable();
oraAdapt.Fill(dt);
con.Close();
con.Dispose();
List<DataRow> dtList = dt.AsEnumerable().ToList();
return Json(dtList, JsonRequestBehavior.AllowGet);
}
Model:
public class GetSDetailsModel
{
public List<GetStudentSearchModel> GetStudentSearchModel { get; set; }
}
public class GetStudentSearchModel
{
public string id { get; set; }
public string name { get; set; }
public string div_code { get; set; }
public string level_code { get; set; }
public string program_code { get; set; }
public string major_code { get; set; }
public string PGPA { get; set; }
}
List<Dictionary<string, object>> arrResponse = new List<Dictionary<string, object>>();
DataTable reader = db.executeQueryDataTable(sSQL);
foreach (DataRow row in reader.Rows)
{
Dictionary<string, object> dictRow = new Dictionary<string, object>();
foreach(DataColumn col in reader.Columns)
dictRow[col.ColumnName] = row[col.ColumnName];
arrResponse.Add(dictRow);
}
the above code turns the DataTable into a serializable List of Dictionary. just serialize arrResponse then
As David said in comment you need to convert DataRow's to List<GetStudentSearchModel>. You can do that using Linq's Select method, passing lambda expression that creates GetStudentSearchModel from DataRow object. The code would be like this:
public JsonResult StudList()
{
string SQL = "select id, name, div_code, block, from students where ....."; //see the below model
var con = DB.GetConnection();
con.Open();
OracleDataAdapter oraAdapt = new OracleDataAdapter(SQL, con);
DataTable dt = new DataTable();
oraAdapt.Fill(dt);
con.Close();
con.Dispose();
List<GetStudentSearchModel> dtList = dt.AsEnumerable()
.Select(row => new GetStudentSearchModel
{
id = row["id"],
name = row["name"],
div_code = row["div_code"],
//...
}).ToList();
return Json(dtList, JsonRequestBehavior.AllowGet);
}
Just add rest of your fields to initializer block.

DataSet does not support System.Nullable<> in Export

I was trying to generate a Report using Export to Excell, PDF, TextFile. Well I am doing this in MVC. I have a class which I named SPBatch (which is the exact name of my Stored Procedure in my SQL) and it contains the following:
public string BatchNo { get; set; }
public string ProviderName { get; set; }
public Nullable<System.Int32> NoOfClaims { get; set; }
public Nullable<System.Int32> TotalNoOfClaims { get; set; }
public Nullable<System.Decimal> TotalBilled { get; set; }
public Nullable<System.Decimal> TotalInputtedBill { get; set; }
public Nullable<System.DateTime> DateCreated { get; set; }
public Nullable<System.DateTime> DateSubmitted { get; set; }
public Nullable<System.DateTime> DueDate { get; set; }
public string Status { get; set; }
public string RefNo { get; set; }
public string BatchStatus { get; set; }
public string ClaimType { get; set; }
as you can see some of my Columns are declared as Nullable. It went smoothly from searching and displaying the results in a table. I have several buttons below which are image buttons for export and every time I try to export in Excel, I always get the problem "DataSet does not support System.Nullable<>" in this part of my code:
foreach (MemberInfo mi in miArray)
{
if (mi.MemberType == MemberTypes.Property)
{
PropertyInfo pi = mi as PropertyInfo;
dt.Columns.Add(pi.Name, pi.PropertyType); //where the error pop's up.
}
else if (mi.MemberType == MemberTypes.Field)
{
FieldInfo fi = mi as FieldInfo;
dt.Columns.Add(fi.Name, fi.FieldType);
}
}
the error shows up on the one with a comment. Can you help me what to do? I tried adding DBNull in my code but still I get the same error. I tried removing Nullable in my SPBatch but I get an error that some tables are need to be declared as Nullable.
What should I do?
try with
dt.Columns.Add(pi.Name, Nullable.GetUnderlyingType(
pi.PropertyType) ?? pi.PropertyType);
Thanks to a C# version of a generating a datatable and some hacking around, I can offer this answer in VB - I put it on here because I've just had a lot of hassle wanting to get a filterable dataset from a stored proc whilst using a simple datalayer. I hope it helps someone else!
Note: The use case is where you wish to use BindingSource.Filter = "some query string":
Imports System.Reflection
Public Module Extenders
<System.Runtime.CompilerServices.Extension>
Public Function ToDataTable(Of T)(collection As IEnumerable(Of T), tableName As String) As DataTable
Dim tbl As DataTable = ToDataTable(collection)
tbl.TableName = tableName
Return tbl
End Function
<System.Runtime.CompilerServices.Extension>
Public Function ToDataTable(Of T)(collection As IEnumerable(Of T)) As DataTable
Dim dt As New DataTable()
Dim tt As Type = GetType(T)
Dim pia As PropertyInfo() = tt.GetProperties()
'Create the columns in the DataTable
For Each pi As PropertyInfo In pia
Dim a =
If(Nullable.GetUnderlyingType(pi.PropertyType), pi.PropertyType)
dt.Columns.Add(pi.Name, If(Nullable.GetUnderlyingType(pi.PropertyType), pi.PropertyType))
Next
'Populate the table
For Each item As T In collection
Dim dr As DataRow = dt.NewRow()
dr.BeginEdit()
For Each pi As PropertyInfo In pia
dr(pi.Name) = If(Nullable.GetUnderlyingType(pi.PropertyType) Is GetType(DateTime), DBNull.Value, pi.GetValue(item, Nothing))
Next
dr.EndEdit()
dt.Rows.Add(dr)
Next
Return dt
End Function
End Module
I would search for nullable and replace it with a string which can be null unlike a DateTime.
foreach (PropertyInfo pi in properties)
{
if (pi.PropertyType.Name.Contains("Nullable"))
myDataType = typeof(String);
else
myDataType = pi.PropertyType;
}
Here is a complete version:
private DataTable CreateDataTable(PropertyInfo[] properties)
{
DataTable dt = new DataTable();
DataColumn dc = null;
foreach (PropertyInfo pi in properties)
{
dc = new DataColumn();
dc.ColumnName = pi.Name;
if (pi.PropertyType.Name.Contains("Nullable"))
dc.DataType = typeof(String);
else
dc.DataType = pi.PropertyType;
// dc.DataType = pi.PropertyType;
dt.Columns.Add(dc);
}
return dt;
}
1) Define This Extensions as Below
public static class ListExtensions
{
public static DataTable ToDataTable<T>(this List<T> list)
{
DataTable table = new DataTable(typeof(T).Name);
//Get Properites of List Fiels
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
//Create Columns as Fields of List
foreach (PropertyInfo propertyInfo in props)
{
var column = new DataColumn
{
ColumnName = propertyInfo.Name,
DataType = propertyInfo.PropertyType.Name.Contains("Nullable") ? typeof(string) : propertyInfo.PropertyType
};
table.Columns.Add(column);
}
//Fill DataTable with Rows of List
foreach (var item in list)
{
var values = new object[props.Length];
for (var i = 0; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
}
table.Rows.Add(values);
}
return table;
}
}
2) Call Extensions Method as Below where [_lstOperationDetails] is List that we want to convert it from List to DataTable
DataTable operationDetails = _lstOperationDetails.ToDataTable();

Get values from LINQ query

How do I get the value of one of the new properties out of query in the DoIt function below?
public object GetData()
{
var table = GetDataTable();
var view = table.DefaultView;
//..... more code
var query = from row in view.ToTable().AsEnumerable()
group row by row.Field<string>("ShortName") into grouping
select new
{
ShortName = grouping.Key,
SCount = grouping.Sum( count => count.Field<int>("ProfCount")),
DisplayText = string.Empty
};
return query;
}
// this code doesn't work
public void DoIt()
{
var result = GetData();
string shortName = result.ShortName;
}
Thanks!
Anonymous types are not called anonymous types for nothing. So:
Define a type with a name (6 additional lines of code):
public class Foo
{
public string ShortName { get; set; }
public int SCount { get; set; }
public string DisplayText { get; set; }
}
Now modify your GetData signature to (0 additional lines of code):
public IEnumerable<Foo> GetData()
And your LINQ query to (3 additional characters, or a couple more if you choose more meaningful name):
var query =
from row in view.ToTable().AsEnumerable()
group row by row.Field<string>("ShortName") into grouping
select new Foo
{
ShortName = grouping.Key,
SCount = grouping.Sum( count => count.Field<int>("ProfCount")),
DisplayText = string.Empty
};
You're returning an anonymous type (via select new {}), which is only valid in the local scope. You need to create a concrete type and return that from your function rather than object.
public SomeClass GetData()
{
var table = GetDataTable();
var view = table.DefaultView;
//..... more code
var query = from row in view.ToTable().AsEnumerable()
group row by row.Field<string>("ShortName") into grouping
select new SomeClass
{
ShortName = grouping.Key,
SCount = grouping.Sum( count => count.Field<int>("ProfCount")),
DisplayText = string.Empty
};
return query;
}
// this code doesn't work
public void DoIt()
{
var result = GetData();
string shortName = result.ShortName;
}
public class SomeClass
{
public string ShortName { get; set; }
public int SCount { get; set; }
public string DisplayText { get; set; }
}
Well, DoIt has no idea that result has a property named ShortName because its typed as an object. You could create a concrete class that holds the results, use reflection, or use dynamic. Note that either way, GetData is really returning an IEnumerable<T> where T is currently an anonymous type.
Using a concrete class:
public class Foo {
public string ShortName { get; set; }
public int SCount { get; set; }
public string DisplayText { get; set; }
}
public IEnumerable<Foo> GetData() {
var table = GetDataTable();
var view = table.DefaultView;
//..... more code
var query = from row in view.ToTable().AsEnumerable()
group row by row.Field<string>("ShortName") into grouping
select new Foo
{
ShortName = grouping.Key,
SCount = grouping.Sum( count => count.Field<int>("ProfCount")),
DisplayText = string.Empty
};
return query;
}
public void DoIt() {
var result = GetData();
foreach(var item in result) {
Console.WriteLine(item.ShortName);
}
}
Using reflection:
public IEnumerable GetData() {
var table = GetDataTable();
var view = table.DefaultView;
//..... more code
var query = from row in view.ToTable().AsEnumerable()
group row by row.Field<string>("ShortName") into grouping
select new Foo
{
ShortName = grouping.Key,
SCount = grouping.Sum( count => count.Field<int>("ProfCount")),
DisplayText = string.Empty
};
return query;
}
public void DoIt() {
var result = GetData();
PropertyInfo property = result.First().GetType().GetProperty("ShortName");
foreach(var item in result) {
string shortName = property.GetValue(item, null);
Console.WriteLine(shortName);
}
}
You can't without using reflection. Since it is an anonymous type, you cannot cast to it in the DoIt() method either, since the type name is not known at compile time.
This gives me what I need:
public object GetData()
{
var table = GetDataTable();
var view = table.DefaultView;
//..... more code
var query = from row in view.ToTable().AsEnumerable()
group row by row.Field<string>("ShortName") into grouping
select new Object[]
{
grouping.Key,
grouping.Sum( count => count.Field<int>("ProfCount")),
string.Empty
};
return query;
}
public void DoIt()
{
// Note: Pretend that GetData returned only one result
object[] result = GetData() as object[];
var shortName = result[0];
}

Object To DataView or DataSet or DataTable and back to object

We have a mish-mash app with a legacy module that still uses DataSets, DataViews and DataTables however we have most of the the databases ORMed except the DB for this Module. I was wondering if someone could give me pointers as to how to go about building extensions like
/* generates a dataset called CustomerDS with
DataTable called Customer uses property names as DataColumn name */
var dataset =_customer.AsDataSet();
/* Converts the dataset to required object or
throws exception if its cant convert*/
var customerEntity = _dataset.ToObject<Customer>();
I dont know when we will get time to work on other layers of the app and free it from DataSets. I might sound crazy but its just a thought. I get nightmares when i need to support/bug fix that app.
You can use a reflection for example:
class Program {
public static void Start( string[] args ) {
var john = new Customer {
CustomerID = Guid.NewGuid(),
CustomerName = "John",
CustomerCode = "J-O"
};
var tblJohn = john.ToDataTable();
var clonedJohn = tblJohn.Rows[0].ToDataObject<Customer>();
}
}
[AttributeUsage(AttributeTargets.Property)]
public class DataColumnAttribute : Attribute { }
public class Customer {
[DataColumn]
public Guid CustomerID { get; set; }
[DataColumn]
public string CustomerName { get; set; }
[DataColumn]
public string CustomerCode { get; set; }
}
public static class DataObjectExtensions {
public static T ToDataObject<T>( this DataRow dataRow ) where T : new() {
var dataObject = Activator.CreateInstance<T>();
var tpDataObject = dataObject.GetType();
foreach ( var property in tpDataObject.GetProperties() ) {
var attributes = property.GetCustomAttributes( typeof( DataColumnAttribute ), true );
if ( null != attributes && attributes.Length > 0 ) {
if ( property.CanWrite ) {
DataColumn clm = dataRow.Table.Columns[property.Name];
if ( null != clm ) {
object value = dataRow[clm];
property.SetValue( dataObject, value, null );
}
}
}
}
return dataObject;
}
public static DataTable ToDataTable( this object dataObject ) {
var tpDataObject = dataObject.GetType();
DataTable tbl = new DataTable();
DataRow dataRow = tbl.NewRow();
foreach ( var property in tpDataObject.GetProperties() ) {
var attributes = property.GetCustomAttributes( typeof( DataColumnAttribute ), true );
if ( null != attributes && attributes.Length> 0 ) {
if ( property.CanRead ) {
object value = property.GetValue( dataObject, null );
DataColumn clm = tbl.Columns.Add( property.Name, property.PropertyType );
dataRow[clm] = value;
}
}
}
tbl.Rows.Add( dataRow );
tbl.AcceptChanges();
return tbl;
}
}
You can use this to get object from data table
public static class Extensions
{
public static List<T> ToList<T>(this DataTable table) where T : new()
{
IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
List<T> result = new List<T>();
foreach (var row in table.Rows)
{
var item = CreateItemFromRow<T>((DataRow)row, properties);
result.Add(item);
}
return result;
}
private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
{
T item = new T();
foreach (var property in properties)
{
if (property.PropertyType == typeof(System.DayOfWeek))
{
DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), row[property.Name].ToString());
property.SetValue(item,day,null);
}
else
{
property.SetValue(item, row[property.Name], null);
}
}
return item;
}
}
and use it like this
List<Employee> lst = ds.Tables[0].ToList<Employee>();

Categories

Resources