When accessing data in C#, the generally accepted way is to use List & Generics. There are many advantages of those such as performance and rich with features such as LINQ to Entities. What if we need a DataTable to be converted into a Entity List? There are easiest ways as discussed here but the following methods will be able to use for easier conversion of DataTables in to relevant Entity List.
These two methods will convert the values in the data table to lists in a way as it used below;
The list can be passed as a return value of the method if needed.
Note that this is only to convert DataTable to a list and if you write a data access method, always try to use DataReader instead of DataTables.
Copy these codes and modify, reuse as needed. :)
public static T? GetValue<T>(this DataRow row, string columnName) where T : struct
{
if (!row.Table.Columns.Contains(columnName))
return null;
if (row.IsNull(columnName))
return null;
return row[columnName] as T?;
} //HANDLE NULLABLE VALUES TOO
public static string GetText(this DataRow row, string columnName)
{
if (!row.Table.Columns.Contains(columnName))
return string.Empty;
if (row.IsNull(columnName))
return string.Empty;
return row[columnName] as string ?? string.Empty;
} //FOR STRINGS
These two methods will convert the values in the data table to lists in a way as it used below;
foreach (var item in dataTable.Select())
{
entityList.Add(new myEntity()
{
id = ExtensionMethods.GetValue<int>(item, "idColumnName").Value,
dateTime = ExtensionMethods.GetValue<DateTime>(item, "dateTimeColumnName").Value,
dateTimeNullable = ExtensionMethods.GetValue<DateTime>(item, "dateTimeNullableColumnName"),
string = ExtensionMethods.GetText(item, "stringColumnName"),
number = ExtensionMethods.GetValue<int>(item, "numberColumnName").Value,
numberNullable = ExtensionMethods.GetValue<int>(item, "numberNullableColumnName")
});
}
The list can be passed as a return value of the method if needed.
Note that this is only to convert DataTable to a list and if you write a data access method, always try to use DataReader instead of DataTables.
Copy these codes and modify, reuse as needed. :)
No comments:
Post a Comment