【发布时间】:2020-04-28 12:42:57
【问题描述】:
我目前正在将 WebForms 应用程序重建为 MVC。这种转换的一部分需要将 DataSets 和 DataTables 映射到对象中。我用来完成此操作的方法是:
public static List<T> DataTableToEntityList<T>(DataTable sourceDataTable, params PropertyMapper[] propertyMappings) where T : class, new()
{
List<T> entityList = new List<T>();
if (sourceDataTable != null)
{
// Get all properties of the Type T
PropertyInfo[] entityProperties = typeof(T).GetProperties();
foreach (DataRow dr in sourceDataTable.Rows)
{
// Create Instance of the Type T
T entity = new T();
PopulateEntityClass<T>(entity, dr, entityProperties, propertyMappings);
entityList.Add(entity);
}
}
return entityList;
}
主程序是:
public static void Main(string[] args)
{
Program program = new Program();
DataTable dt = program.createData();
List<superadminAction> list = Helper.DataMappingHelper.DataTableToEntityList<superadminAction>(dt, null);
foreach(superadminAction action in list)
{
if (action.Title != null)
Console.WriteLine(action.Title);
else
Console.WriteLine("null values");
}
Console.ReadLine();
}
我要转换的对象是:
public class superadminAction
{
public int SuperAdminActionCounter;
public string Procedure, Title, Description, TemplateDescription;
}
}
我不知道为什么我无法访问 Main(...) 函数中的属性。
任何想法都将不胜感激。
【问题讨论】:
-
可能是因为你在
superadminAction类中没有属性 -
没有属性不会抛出异常;它会返回一个空数组。
-
@madreflection 我猜,这个异常发生在
PopulateEntityClass<T>(entity, dr, entityProperties, propertyMappings);调用中的某个地方。 @urizark 你还为propertyMappings传递了一个null值 -
@PavelAnikhouski:也许吧,但这不是问题所说的。它指出
typeof(T)抛出异常,我们看到在调用PopulateEntityClass<T>之前。 -
@madreflection 绝对,我现在就这样做。感谢您的帮助
标签: c# asp.net-mvc webforms dataset typeof