Monday, June 2, 2014

Entity Framework: SqlQuery does not support mapping

I had a simple query that I wanted to execute directly. I didn’t want to introduce any extra ADO.NET related classes so I used the SqlQuery<T> method that is available on the Entity Framework DbContext. If you want to have an Entity returned than this is easy. Just use the SqlQuery<> method on your DBSet<>:

If you don’t want an Entity returned but just a random class, you can use the SqlQuery<> method on the Database object:

Still easy to do…

There is however an important remark: the columns returned from your query should exactly match the property names of your objects. There is (at the moment) no way to specify a mapping between your custom class and a query.  Of course you can always use a column alias (AS keyword in SQL Server) to rename the column in the results.

No comments: