在我的操作方法中,我运行以下查询,该查询返回一个列表:
y
我有一个相同格式的viemodel,如下所示:
var list = db.WorkRoles.
Join(db.WorkRolesUsersDetails,
o => o.WorkRoleId, od => od.WorkRoleId,
(o, od) => new
{
WorkRoleId = o.WorkRoleId,
RoleName = o.RoleName,
RoleDescription = o.RoleDescription,
CompanyId = o.CompanyId,
WRUDId = od.WRUDId,
UserDetailsId = od.UserDetailsId,
FocusStart = od.FocusStart,
FocusEnd = od.FocusEnd
}).ToList();
将查询结果转换为viewmodel列表的最佳方法是什么?
答案 0 :(得分:1)
如果您不希望您的操作方法知道View Model类型,那么您可以尝试以下操作。
Select
,并为每个项目构建RoleViewModel
。使用AutoMapper库为您完成这项工作。
var list = db.WorkRoles.
Join(db.WorkRolesUsersDetails,
o => o.WorkRoleId, od => od.WorkRoleId,
(o, od) => new
{
WorkRoleId = o.WorkRoleId,
RoleName = o.RoleName,
RoleDescription = o.RoleDescription,
CompanyId = o.CompanyId,
WRUDId = od.WRUDId,
UserDetailsId = od.UserDetailsId,
FocusStart = od.FocusStart,
FocusEnd = od.FocusEnd
}).ToList()
.Select(item => new RoleViewModel(
item.WorkRoleId,
item.RoleName,
item.RoleDescription,
item.CompanyId,
item.WRUDId,
item.UserDetailsId,
item.FocusStart,
item.FocusEnd));
答案 1 :(得分:1)
var list = db.WorkRoles.
Join(db.WorkRolesUsersDetails,
o => o.WorkRoleId, od => od.WorkRoleId,
(o, od) => new RoleViewModel(
o.WorkRoleId,
o.RoleName,
o.RoleDescription,
o.CompanyId,
od.WRUDId,
od.UserDetailsId,
od.FocusStart,
od.FocusEnd
)).ToList();