如何解决 - 无法使用Automapper将Generic.List转换为Linq.IQueryable? [英] How to resolve - unable to cast Generic.List to Linq.IQueryable using Automapper?
问题描述
使用DTO和EF模型时,我收到以下错误:
I'm getting the following error in using a DTO and EF model:
无法投射类型为
的对象'System.Collections.Generic.List1 [Project.Core.UI.Models.ContentTypes]'
1 [项目。 Core.UI.Models.ContentTypes]
键入'System.Linq.IQueryable
Unable to cast object of type 'System.Collections.Generic.List
1[Project.Core.UI.Models.ContentTypes]' to type 'System.Linq.IQueryable
1[Project.Core.UI.Models.ContentTypes]
引导: Mapper.CreateMap< ContentType,Project.Core.UI .Models.ContentTypes>();
在一个OData控制器方法 public IQueryable< ContentTypes> Get(){...}
,使用:
In an OData controller method public IQueryable<ContentTypes> Get() {...}
, using:
var result = Mapper.Map<IQueryable<ContentType>, IQueryable<ContentTypes>>(_repository.Query().Get()
.Where(u => u.UserId == userId)
.OrderBy(o => o.Description));
我也尝试了以下内容,但我怀疑这正是上面的一样: / p>
I have also tried the following but I suspect that this is exactly what the above is as well:
var result =_repository.Query().Get()
.Where(u => u.UserId == userId)
.OrderBy(o => o.Description);
var dto = Mapper.Map<IQueryable<ContentType>, IQueryable<ContentTypes>>(result);
return dto;
如何为此创建适当的映射?
How can I create the appropriate mapping for this?
推荐答案
您需要注意的事实是,通过以下方式创建映射:
You need to be aware of the fact that by creating your mapping in such a way:
Mapper.CreateMap<ContentType, Project.Core.UI.Models.ContentTypes>();
只有这些基本的通用集合类型才能被隐含地支持:
Only these basic generic collection types are supported implicitly:
IEnumerable
IEnumerable<T>
ICollection
ICollection<T>
IList
IList<T>
List<T>
Arrays
但不是 IQueryable< T>
。这就是为什么你得到例外。
But not IQueryable<T>
. That's why you get the exception.
所以你应该尝试这样做:
Therefore you should try doing sth like this:
var dto = Mapper.Map
<IEnumerable<ContentType>,
IEnumerable<ContentTypes>>(result.AsEnumerable());
// or e.g. List/List/ToList()
这篇关于如何解决 - 无法使用Automapper将Generic.List转换为Linq.IQueryable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!