如何使用LLBLGen从DataTable加载EntityCollection或List(Of Entity)?
答案 0 :(得分:2)
数据表将其值保存在行和列中,而LLBLGen Collection类包含一组Entity对象,这些对象表示持久存储中的表。您可以通过TypedListDAO获取使用ResultsetField定义的字段的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();