嵌套模型我有一個已經存在的類創建一個從列表
public class Employee
{
public int? EmployeeId { get; set; }
public string EmployeeName { get; set; }
public int? LocationId { get; set; }
public string LocationName { get; set; }
public int? DesignationId { get; set; }
public string DesignationName { get; set; }
}
代碼從數據庫中獲取數據:
using (var ds = new EmployeeDS())
{
using (var dataAdapter = new DataSet.EmployeeDSTableAdapters.EmployeeTableAdapter())
{
dataAdapter.FillEmployee(ds.Employee,Id);
var result = (from DataRow row in ds.Employee.Rows
select new Employee
{
EmployeeId = (row["EmployeeID"] == DBNull.Value) ? null : (int?)row["EmployeeID"],
EmployeeName = (row["EmployeeName"] == DBNull.Value) ? string.Empty : (string)row["EmployeeName"],
LocationId = (row["LocationId"] == DBNull.Value) ? null : (int?)row["LocationId"],
LocationName = (row["LocationName"] == DBNull.Value) ? string.Empty : (string)row["LocationName"],
DesignationId = (row["DesignationId"] == DBNull.Value) ? null : (int?)row["DesignationId"],
DesignationName = (row["DesignationName"] == DBNull.Value) ? string.Empty : (string)row["DesignationName"],
}).ToList();
}
}
其工作fine.But的員工該返回多行具有多個位置或所以我需要返回數據爲嵌套模型,如:
public class EmployeeNested
{
public int? EmployeeId { get; set; }
public string EmployeeName { get; set; }
public List<Location> Locations { get; set; }
public List<Designation> Designations { get; set; }
}
public class Location
{
public int? LocationId { get; set; }
public string LocationName { get; set; }
}
public class Designation
{
public int? DesignationId { get; set; }
public string DesignationName { get; set; }
}
我是usi NG驗證碼返回嵌套模式:
var tempList=result.GroupBy(x => x.EmployeeId, (key, g) => g.OrderBy(e => e.EmployeeId).First());
foreach (var item in tempList)
{
item.Designations = result
.Where(x => x.EmployeeId== item.EmployeeId)
.Select(x => new Designation
{
DesignationId = x.DesignationId,
DesignationName = x.DesignationName
}).ToList();
item.Locations = result
.Where(x => x.EmployeeId== item.EmployeeId)
.Select(x => new Location
{
LocationId = x.LocationId,
LocationName = x.LocationName
}).ToList();
}
問:
有沒有更好的解決方案,以扁平列表轉換爲嵌套表?
是否有可能創建一個通用的方法來將平板列表轉換爲 嵌套列表?這樣我就可以將它重用於其他功能。
是否可以直接從數據集創建嵌套列表?
我確信有這樣一個很好的可靠模式,我只是找不到它。
不,表格之間沒有關係。並且還在整個項目中使用了數據集。所以我做了什麼是正確的方式來實現嵌套列表? – Binu