如何使用 LLBLGen 从 DataTable 加载 EntityCollection 或 List(Of Entity)?
问问题
2092 次
1 回答
2
数据表将其值保存在行和列中,而 LLBLGen 集合类保存表示持久存储中的表的实体对象的集合。您可以通过 TypedListDAO 获取使用 ResultsetFields 定义的字段的 DataTable。但是,除非您的 Entity 对象存储在您的 DataTable 中,否则无法从 DataTable 转到 EntityCollection。
更有可能的是,您的 DataTable 中有一些键。如果是这种情况,您将需要遍历 DataTable 的行,取出键并从中创建新的 Entity 对象。然后您可以将这些 Entity 对象添加到您的 EntityCollection。
// Define the fields that we want to get
ResultsetFields fields = new ResultsetFields(2);
fields.DefineField(EmployeeFields.EmployeeId, 0);
fields.DefineField(EmployeeFields.Name, 1);
// Fetch the data from the db and stuff into the datatable
DataTable dt = new DataTable();
TypedListDAO dao = new TypedListDAO();
dao.GetMultiAsDataTable(fields, dt, 0, null, null, null, false, null, null, 0, 0);
// We now have a datatable with "EmployeeId | Name"
// Create a new (empty) collection class to hold all of the EmployeeEntity objects we'll create
EmployeeCollection employees = new EmployeeCollection();
EmployeeEntity employee;
foreach(DataRow row in dt.Rows)
{
// Make sure the employeeId we are getting out of the DataTable row is at least a valid long
long employeeId;
if(long.TryParse(row["EmployeeId"].ToString(), out employeeId))
{
// ok-looking long value, create the Employee entity object
employee = new EmployeeEntity(employeeId);
// might want to check if this is .IsNew to check if it is a valid object
}
else
{
throw new Exception("Not a valid EmployeeId!");
}
// Add the object to the collection
employees.Add(employee);
}
// now you have a collection of employee objects...
employees.DoStuff();
于 2011-06-06T02:32:10.880 回答