嵌套模型我有一个已经存在的类创建一个从列表
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