AutoMapper 3.1.1 and Entity Framework 6.1 Proxy objects

回眸只為那壹抹淺笑 提交于 2020-01-11 06:16:42

问题


I realized this has been asked already, but the solutions I've read don't seem to make a difference so far. I'm using Entity Framework 6.1 and AutoMapper 3.1.1. Taking the following objects: Company and CompanyListItem; I try this:

Mapper.Configure<Company, CompanyListItem>();

Well, when I try to do the actual mapping it crashed and burned with an exception that there's no mappings defined. I know this is caused because of the proxy objects created by Entity Framework. One solutions I've seen so far is to call an overloaded version of the Map method:

IQueryable<Company> companies = CompaniesService.FindCompanies();

Mapper.Map(companies, typeof(Company[]), typeof(CompanyListItem[]));

And it still doesn't work and yells at me.

I've also read other posts that this has been fixed as of 2.2.1? Is this different or did it regress? I'd appreciate suggestions.


回答1:


You are using Automapper incorrectly, you need to use the QueryableExtensions namespace, so your code should be

IQueryable<Company> companies = CompaniesService.FindCompanies();

CompanyListItem[] results = companies.Project().To<CompanyListItem>().ToArray();

Also if you where going to do it the other way you still had Mapper.Map wrong, it should have been

IQueryable<Company> companies = CompaniesService.FindCompanies();

CompanyListItem[] result = Mapper.Map<IEnumerable<Company>,CompanyListItem[]>(companies);

but I still recommend doing the .Project().To<T>() method as it will perform the mapping server side instead of client side so you potentially have less data that needs to be sent over the wire.



来源:https://stackoverflow.com/questions/22723133/automapper-3-1-1-and-entity-framework-6-1-proxy-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!