寻找关于最佳方法/模式的输入,以满足视图模型类的以下要求:
我正在尝试的例子,但它不起作用......似乎有点像黑客:
public class WorkOrderDependencyViewModel : IEntity, IViewModel<WorkOrderDependency, WorkOrderDependencyViewModel>
{
public int Id { get; set; } }
public int WorkOrderHeaderId { get; set; }
public int POHeaderId { get; set; }
public decimal RemainQty { get; set; }
//Re-use this mapping logic for both converting a query and converting a single db entity instance. Used by Kendo Grids
public IQueryable<WorkOrderDependencyViewModel> ConvertClassQueryToViewModelQuery(IQueryable<WorkOrderDependency> entityQuery)
{
var viewModelResultQuery = entityQuery
.Select(x => new WorkOrderDependencyViewModel()
{
Id = x.Id,
WorkOrderHeaderId = x.WorkOrderHeaderId,
POHeaderId = x.PODetail.POHeaderId,
RemainQty = x.PODetail.QtyOrdered - x.PODetail.QtyReceived
}
);
return viewModelResultQuery;
}
//convert single instance of db entity to view model, but use existing mapping logic from above method
public WorkOrderDependencyViewModel ConvertClassToViewModel(WorkOrderDependency entity)
{
var entityList = new List<WorkOrderDependency>();
entityList.Add(entity);
var viewModel = ConvertClassQueryToViewModelQuery(entityList.AsQueryable()).FirstOrDefault() as WorkOrderDependencyViewModel;
return viewModel; <------ viewModel is NULL
}
}
为什么viewModel返回NULL?
答案 0 :(得分:1)
如果您不需要IQueryable,这将是一个更短更简单的方法
public WorkOrderDependencyViewModel ConvertClassToViewModel(
WorkOrderDependency entity)
{
return new WorkOrderDependencyViewModel
{
Id = entity.Id,
WorkOrderHeaderId = entity.WorkOrderHeaderId,
POHeaderId = entity.PODetail.POHeaderId,
RemainQty = entity.PODetail.QtyOrdered - entity.PODetail.QtyReceived
};
}
修改强> 如果你使用它作为linq查询的一部分,也许你可以使用Automapper或像这样的函数
private static readonly Expression<Func<WorkOrderDependency, WorkOrderDependencyViewModel>> AsViewModel =
entity => new WorkOrderDependencyViewModel
{
Id = entity.Id,
WorkOrderHeaderId = entity.WorkOrderHeaderId,
POHeaderId = entity.PODetail.POHeaderId,
RemainQty = entity.PODetail.QtyOrdered - entity.PODetail.QtyReceived
};
您可以在查询中使用它
public IQueryable<WorkOrderDependencyViewModel> GetViewModel()
{
return repository.WorkOrderDependencies // change to suit your query needs
.Select(AsViewModel);
}