视图模型创建的最佳方法是处理单个实体和列表 - 返回IQueryable

时间:2014-10-15 01:54:33

标签: c# asp.net-mvc entity-framework linq-to-entities

寻找关于最佳方法/模式的输入,以满足视图模型类的以下要求:

  • 将IQueryable从存储库选择转换为IQueryable视图模型查询< - 正常工作
  • 将db实体的单个实例转换为视图模型实例< - 不工作,返回NULL
  • 两者都使用单个方法将db实体映射到视图模型属性以避免映射复制

我正在尝试的例子,但它不起作用......似乎有点像黑客:

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?

1 个答案:

答案 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);

}