Kayra
Kayra

Reputation: 165

Can't get data out using SQL query in Entity Framework

I'm trying to use the following SQL query to get the first two columns of data out of my database:

SELECT  Id, DomainUrl
FROM    ( SELECT    ROW_NUMBER() OVER ( ORDER BY Id ) AS RowNum, Id, DomainUrl
          FROM      SiteDatas
        ) AS RowConstrainedResult
WHERE   RowNum >= 1
    AND RowNum <= 10
ORDER BY RowNum

I'm using entity framework and passing in parameters for the rows so that it can later be used as a scroll on load function via ajax. However I am getting an error when I get to the line:

var stores = db.SiteDatas.SqlQuery(SQL, parameters).ToList();

It's an entity command execution exception that is stating that the data reader is incompatible with the specified model (my db) member of the type, 'Robots' (which is the next column after the one I am calling), does not have a corresponding column in the data reader with the same name.

How would I go about getting just the first two columns out in a way that can be serialized as json?

Upvotes: 3

Views: 10561

Answers (1)

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131364

The DbSet.SqlQuery and Database.SqlQuery commands both return entity instances. Your sql query has to return the same columns as your entity. Most probably, your SiteData class contains a Robots column that doesn't exist in your SQL query.

You can still use Database.SqlQuery< T > to return your data, provided you specify the return type. The return type doesn't have to be an entity type, just have the same column names as your result set.

Assuming db is a DbContext instance, you can write:

public class MyResults
{
   public int ID{get;set;}
   public string DomainUrl {get;set;}
}

...

var stores = db.Database.SqlQuery<MyResults>(SQL, parameters).ToList();

Upvotes: 7

Related Questions