How to write a generic function that takes datarow and populate the properties of an object?

I have some function like

private static UserInfo FillUserInfoFromDataRow(DataRow dr) { UserInfo user = new UserInfo(); user.UserID = (int) dr["UserID"]; user.UserName = (int) dr["UserName"]; user.ProjectID = (int) dr["ProjectID"]; user.ClassID = (int) dr["ClassID"]; .............. return user; } 

I would like to write some general function, for example private static T FillEntityInfoFromDataRow (DataRow dr), which will handle the similar types of ProjectInfo, JobInfo, etc.

I can get all the column names of the DataRow parameter, but I don’t know how to get all the corresponding fields of a general type T and how to perform the corresponding casting. Is this some way to make this work? Thanks!

Ilan.

+4
source share
3 answers

It is better to use reflection, there are no examples available for google for this.

Check the example below

 namespace MyNamespace.Data { class Converter { public static void Fill(object LogicObject, DataRow Row) { Dictionary<string, PropertyInfo> props = new Dictionary<string,PropertyInfo>(); foreach (PropertyInfo p in LogicObject.GetType().GetProperties()) props.Add(p.Name, p); foreach (DataColumn col in Row.Table.Columns) { string name = col.ColumnName; if (Row[name] != DBNull.Value && props.ContainsKey(name)) { object item = Row[name]; PropertyInfo p = props[name]; if (p.PropertyType != col.DataType) item = Convert.ChangeType(item, p.PropertyType); p.SetValue(LogicObject, item, null); } } } } } 

Scan the full blog post: http://kasey-jo.blogspot.com/2009/04/using-reflection-to-fill-business-layer.html

+10
source

I am using this, which seems like what you need:

EDITED thanks to Heinzi

  public virtual void LoadDataRow(DataRow drow, params string[] parameters) { this.LoadDataRow(drow); foreach (string property in parameters) { try { if (drow[property] != null) { PropertyInfo pi = this.GetType().GetProperty(property); if (pi != null && drow.Table.Columns.Contains(property)) { pi.SetValue(this, drow[property], null); } } } catch { throw; } } } 

In your case, however, you can first skip the first eproperty collection of your object and try loading from your dataset, but you need to start with this code.

EDIT

This is detected on MSDN:

 System.Reflection.PropertyInfo[] p = MyObject.GetType.GetProperties(); foreach(System.Reflection.PropertyInfo prop in p) { .... } 
+1
source

Pass this functionality to each class by declaring the abstarct method in the base class. By the way, I suggest calling this method as CreateFromDataRow()

 abstract class InfoBase { public abstract InfoBase CreateFromDataRow(DataRow dr); } 

OR

 abstract class InfoBase<T> { public abstract T CreateFromDataRow(DataRow dr); } 
0
source

All Articles