I am very interested in Linq to SQL with Lazy load feature. And in my project I used AutoMapper to map DB Model to Domain Model (from DB_RoleInfo
to DO_RoleInfo
). In my repository code as below:
public DO_RoleInfo SelectByKey(Guid Key) { return SelectAll().Where(x => x.Id == Key).SingleOrDefault(); } public IQueryable<DO_RoleInfo> SelectAll() { Mapper.CreateMap<DB_RoleInfo, DO_RoleInfo>(); return from role in _ctx.DB_RoleInfo select Mapper.Map<DB_RoleInfo, DO_RoleInfo>(role); }
SelectAll
method is run well, but when I call SelectByKey
, I get the error:
Method “RealMVC.Data.DO_RoleInfo MapDB_RoleInfo,DO_RoleInfo” could not translate to SQL.
Is it that Automapper doesn't support Linq completely?
Instead of Automapper, I tried the manual mapping code below:
public IQueryable<DO_RoleInfo> SelectAll() { return from role in _ctx.DB_RoleInfo select new DO_RoleInfo { Id = role.id, name = role.name, code = role.code }; }
This method works the way I want it to.
AutoMapper is a simple library that helps us to transform one object type into another. It is a convention-based object-to-object mapper that requires very little configuration. The object-to-object mapping works by transforming an input object of one type into an output object of a different type.
Inside this article, it discusses performance and it indicates that Automapper is 7 times slower than manual mapping.
AutoMapper is used whenever there are many data properties for objects, and we need to map them between the object of source class to the object of destination class, Along with the knowledge of data structure and algorithms, a developer is required to have excellent development skills as well.
While @Aaronaught's answer was correct at the time of writing, as often the world has changed and AutoMapper with it. In the mean time, QueryableExtensions
were added to the code base which added support for projections that get translated into expressions and, finally, SQL.
The core extension method is ProjectTo
1. This is what your code could look like:
using AutoMapper.QueryableExtensions; public IQueryable<DO_RoleInfo> SelectAll() { Mapper.CreateMap<DB_RoleInfo, DO_RoleInfo>(); return _ctx.DB_RoleInfo.ProjectTo<DO_RoleInfo>(); }
and it would behave like the manual mapping. (The CreateMap
statement is here for demonstration purposes. Normally, you'd define mappings once at application startup).
Thus, only the columns that are required for the mapping are queried and the result is an IQueryable
that still has the original query provider (linq-to-sql, linq-to-entities, whatever). So it is still composable and this will translate into a WHERE
clause in SQL:
SelectAll().Where(x => x.Id == Key).SingleOrDefault();
1Project().To<T>()
prior to v. 4.1.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With