Click here to Skip to main content
15,884,176 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am working on Web API controllers with EF. When i use a single table like following code am getting the JSON object correctly.

XML
static IEnumerable<ProductIdAndName> SelectTop5ProductsIdAndName()
  {
    NorthwindEntities northwindEntities = new NorthwindEntities();
    string nativeSQLQuery =
      "SELECT TOP 5 ProductID as ID, ProductName as Name " +
      "FROM dbo.Products " +
      "ORDER BY ProductID";
    ObjectResult<ProductIdAndName> products =
      northwindEntities.ExecuteStoreQuery<ProductIdAndName>(nativeSQLQuery);
    return products;
  }


When i use two tables i wrote like following because i am getting values from multiple tables.

XML
static IEnumerable<Object> SelectTop5ProductsIdAndName()
  {
    NorthwindEntities northwindEntities = new NorthwindEntities();
    string nativeSQLQuery =
      "SELECT TOP 5 * FROM dbo.Products, dbo.ProductsPrice ORDER BY ProductID";
    ObjectResult<Object> products =
      northwindEntities.ExecuteStoreQuery<Object>(nativeSQLQuery);
    return products;
  }


In this case am not able to get the JSON, as the return type is of object. Please give suggestios to solve this.
Note: I am not interested in creating viewmodels.
Posted
Updated 4-Aug-14 0:20am
v2

1 solution

Few things I noticed

1. Using EF and writing a SQL query inline is bad. You don't have to explicitly write sql queries
2. The following query might work for you but it's not a good practice. Say if you really want to use sql queries with multiple tables, user inner/outer joins
SELECT TOP 5 * FROM dbo.Products, dbo.ProductsPrice ORDER BY ProductID


Coming to the solution. Build a viewmodel or a class to hold the results of both tables. You should fetch and return the viewmodel.

Let me know if you have any doubts.

Thanks,
 
Share this answer
 
v2
Comments
Kumarbs 20-Jun-14 0:15am    
Thank you for the solution. I know that writing query is a bad practice, but i am working on migration project so it is the only way i found :(.
And am using WEB API.
Well, i don't want to create a class again for the query as i mentioned in the question, because i am going to work with plenty of queries so for each query if i create a class, it might become app size more and moreover i won't know what are the fields we are going to retrieve as every query is dynamically getting from different sources. Could you please provide another way to solve it?

Thanks in advance.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900