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<>:
using (var context = new BloggingContext()) | |
{ | |
var blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList(); | |
} |
If you don’t want an Entity returned but just a random class, you can use the SqlQuery<> method on the Database object:
public class BlogInfo | |
{ | |
public string Name{get;set;} | |
public DateTime Date{get;set;} | |
} |
using (var context = new BloggingContext()) | |
{ | |
var blogInfo = context.Database.SqlQuery<BlogInfo>( | |
"SELECT Name, Date FROM dbo.Blogs").ToList(); | |
} |
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.