EF: How to execute a SQL-query with multiple joins?

蓝咒 提交于 2019-12-12 10:13:42

问题


Im working with Entity Framework version 6.1.3 and I want to execute a SQL-query which gathers information from multiple tables like this:

var result = context.Database.SqlQuery<SomeType>("SELECT SUM(d.PurchaseValue) AS 'Total', div.Name, l.Name " +
                                                  "FROM Device AS d " +
                                                  "RIGHT JOIN Location AS l " +
                                                  "ON d.LOCATION_ID = l.ID " +
                                                  "RIGHT JOIN Division AS div " +
                                                  "ON d.DIVISION_ID = div.ID " +
                                                  "GROUP BY div.Name, l.Name " +
                                                  "ORDER BY l.Name");

My question is, what should be the the type in SqlQuery<>? Or what is the proper way to execute a query like this and get a result out of it?


回答1:


Hi Newb

Here Type can be any type that has properties that match the names of the columns returned from the query.

For Example

Your Query returns columns

Total | Name

So your return type can be like below

public class Sample
{
    public string Name { get; set; }
    public decimal Total { get; set; }
}

Your Query call will be

var result = context.Database.SqlQuery<List<Sample>>(...);



回答2:


Have you seen checked the Data Development Center for ways to do this?

Note 'Entity Framework allows you to query using LINQ with your entity classes. However, there may be times that you want to run queries using raw SQL directly against the database.'

So if you can, use LINQ. Check here and here to start.



来源:https://stackoverflow.com/questions/39795192/ef-how-to-execute-a-sql-query-with-multiple-joins

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