Click here to Skip to main content
14,240,247 members
Rate this:
Please Sign up or sign in to vote.
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.

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.

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

Rate this:
Please Sign up or sign in to vote.

Solution 1

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,
   
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100