1

我有具有以下定义的域类

public class Category : EntityBase<int>
{     
    public string Name { get; set; }
    public string Description { get; set; }
}

而且这个类继承自一个普通的抽象类

public abstract class EntityBase<TId>
{
    public TId Id { get; set; }
}

我的这种类型的 ServiceModel 类看起来像

public class CategoryDto
{
    public string Name { get; set; }
    public string Description { get; set; }
    public int CategoryId { get; set; }
}

在我使用自动映射器的对象之间进行转换。我像这样配置了自动映射器

public class AutoMapperServiceConfigurations
{
    public static void Configure()
    {
        Mapper.Initialize(conf => conf.AddProfile(new CategoryProfile()));
    }
}

public class CategoryProfile : Profile
{
    protected override void Configure()
    {
        Mapper.CreateMap<Category,CategoryDto>();
    }
}

当我在我的代码中使用自动映射器时转换对象,它显示了一些错误,我的代码如下

var categoryCollection= _categoryRepository.Get<Category>();

// Mapping section here i got error
var returnCollection = 
    Mapper.Map<IQueryable<Category>, IQueryable<CategoryDto>> (categoryCollection); 
return returnCollection;

错误是

<Error><Message>An error has occurred.</Message><ExceptionMessage>
Unable to cast object of type
'System.Collections.Generic.List`1[PCD.Service.ServiceModels.CategoryDto]' to type     'System.Linq.IQueryable`1[PCD.Service.ServiceModels.CategoryDto]'.
</ExceptionMessage><ExceptionType>System.InvalidCastException</ExceptionType><StackTrace>   at AutoMapper.MappingEngine.Map[TSource,TDestination](TSource source)
   at AutoMapper.Mapper.Map[TSource,TDestination](TSource source)
   at PCD.Service.Implimentations.CategoryService.Read[T]() in g:\AngularJs Practise\ProofOfConceptDemo.Solution\PCD.Service\Implimentations\CategoryService.cs:line 50
   at PCD.WebApi.Controllers.CategoryController.Get() in g:\AngularJs Practise\ProofOfConceptDemo.Solution\PCD.WebApi\Controllers\CategoryController.cs:line 23
   at lambda_method(Closure , Object , Object[] )
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.<>c__DisplayClass5.<ExecuteAsync>b__4()
   at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)</StackTrace></Error>
4

1 回答 1

0

您将需要使用可查询的扩展:

http://docs.automapper.org/en/stable/Queryable-Extensions.html

  var categoryCollection = _categoryRepository.Get<Category>();

  var returnCollection = categoryCollection.ProjectTo<CategoryDto>();

  return returnCollection.ToList();
于 2018-08-08T09:01:51.703 回答