尝试使用Automapper的IQueryable扩展。
以下代码:
class Program
{
public class A { public string[] Strings { get; set; } }
public class B { public string[] Lines { get; set; } }
static void Main(string[] args)
{
Mapper.CreateMap<A, B>()
.ForMember(m => m.Lines, action => action.MapFrom(src => src.Strings));
IQueryable<A> qa = (new List<A>() {new A() {Strings = new string[0]}}).AsQueryable();
IQueryable<B> b = qa.Project().To<B>(); // error is here
}
}
给出错误“序列不包含任何元素”。这是因为这一行:
.ForMember(m => m.Lines, action => action.MapFrom(src => src.Strings));
我做错了什么?我知道这种特殊情况有一个更简单的解决方案但我每次使用“.MapFrom”方法使用集合时都会遇到这种麻烦。
STack追踪说:
at System.Linq.Enumerable.First [TSource](IEnumerable
1 source)
2.GetOrAdd(TKey) key,Func
at AutoMapper.MappingEngine.CreateMapExpression(Type typeIn, Type typeOut) at AutoMapper.MappingEngine.<CreateMapExpression>b__9[TSource,TDestination](TypePair tp) at System.Collections.Concurrent.ConcurrentDictionary2 valueFactory) at AutoMapper.MappingEngine.CreateMapExpression[TSource,TDestination]()
1.ToTResult in d:\工作\杂项\ VS \ ConsoleApplication1 \ ConsoleApplication1 \的Program.cs:行 57在ConsoleApplication1.Program.Main(String [] args)中 d:\工作\杂项\ VS \ ConsoleApplication1 \ ConsoleApplication1 \的Program.cs:行 21在System.AppDomain._nExecuteAssembly(RuntimeAssembly程序集, System.AppDomain.ExecuteAssembly上的String [] args)(String assemblyFile,Evidence assemblySecurity,String [] args)at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at ConsoleApplication1.ProjectionExpression
在System.Threading.ThreadHelper.ThreadStart_Context(对象状态)
在System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext,ContextCallback回调,对象状态,布尔值 preserveSyncCtx)at System.Threading.ExecutionContext.Run(执行上下文 executionContext,ContextCallback回调,对象状态,布尔值 preserveSyncCtx)at System.Threading.ExecutionContext.Run(执行上下文 executionContext,ContextCallback回调,对象状态)at System.Threading.ThreadHelper.ThreadStart()
所以它在某个时刻执行First()。为什么?怎么解决?
感谢。