无法在asp.net mvc 3.0中编写正确的函数

时间:2011-06-10 06:57:14

标签: c#

我有一种方法,它将返回IQueryable值

public IQueryable<TabMasterViewModel> Query(Expression<Func<TabMaster, bool>> whereCondition)
{
    IQueryable<TabMaster> tabmasters = _tabmasterRepository.GetQueryable().Where(whereCondition);
    IQueryable<TabMasterViewModel> tabmasterview;
    AutoMapper.Mapper.CreateMap<TabMaster, TabMasterViewModel>()
        .ForMember(dest => dest.colID, opt => opt.MapFrom(src => src.colID));
    tabmasterview = AutoMapper.Mapper.Map(tabmasters, tabmasterview);
    return tabmasterview;
}

GetQueryable 就像

public IQueryable<T> GetQueryable()
{
    return this.ObjectSet.AsQueryable<T>();
}

但是以下一行

tabmasterview = AutoMapper.Mapper.Map(tabmasters, tabmasterview);

给我一​​个错误

使用未分配的本地变量'tabmasterview'

请建议我,我哪里错了?

1 个答案:

答案 0 :(得分:1)

要修复编译器错误,您只需要

 IQueryable<TabMasterViewModel> tabmasterview = null;

但是传递给AutoMapper.Mapper.Map(tabmasters, tabmasterview)的第二个参数始终为null,因为tabMasterview尚未初始化。如果是这样的话你也可以通过“null”。

public IQueryable<TabMasterViewModel> Query(Expression<Func<TabMaster, bool>> whereCondition)
        {
            IQueryable<TabMaster> tabmasters = _tabmasterRepository.GetQueryable().Where(whereCondition);

            AutoMapper.Mapper.CreateMap<TabMaster, TabMasterViewModel>()
                  .ForMember(dest => dest.colID, opt => opt.MapFrom(src => src.colID));
            return AutoMapper.Mapper.Map<IQueryable<TabMaster>,  IQueryable<TabMasterViewModel>> (tabmasters);            
        }

编辑:

以上代码回答了与编译器错误相关的问题。 至于你对运行时错误的评论..修改这一行

return AutoMapper.Mapper.Map<IQueryable<TabMaster>,  IQueryable<TabMasterViewModel>> (tabmasters);   

return AutoMapper.Mapper.Map<IQueryable<TabMaster>,  IEnumerable<TabMasterViewModel>> (tabmasters).AsQueryable<TabMasterViewModel>();