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

c# entity-framework sql

Question

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?

1
3
7/16/2013 10:02:27 AM

Accepted Answer

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();
7
7/16/2013 10:26:04 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow