[英]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: 我正在尝试使用以下SQL查询从我的数据库中获取前两列数据:
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. 我正在使用实体框架并为行传入参数,以便稍后可以通过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? 我怎么能以一种可以序列化为json的方式获得前两列?
The DbSet.SqlQuery and Database.SqlQuery commands both return entity instances. DbSet.SqlQuery和Database.SqlQuery命令都返回实体实例。 Your sql query has to return the same columns as your entity.
您的SQL查询必须返回与您的实体相同的列。 Most probably, your SiteData class contains a
Robots
column that doesn't exist in your SQL query. 最有可能的是,您的SiteData类包含SQL查询中不存在的
Robots
列。
You can still use Database.SqlQuery< T > to return your data, provided you specify the return type. 如果指定了返回类型,仍可以使用Database.SqlQuery <T>返回数据。 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: 假设
db
是DbContext
实例,您可以编写:
public class MyResults
{
public int ID{get;set;}
public string DomainUrl {get;set;}
}
...
var stores = db.Database.SqlQuery<MyResults>(SQL, parameters).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.