[英]Entity Framework Database query results in NULL values
I am creating a WPF app using C#, Entity Framework and SQL Server 2008 R2. 我正在使用C#,实体框架和SQL Server 2008 R2创建WPF应用。 I am trying to fire the following query.
我正在尝试触发以下查询。
Select Convert(nvarchar(10),bk.BookingDate,103) as Date, Count(*)
from Booking bk
where
Convert(date,bk.BookingDate) between '2014-10-01' and '2014-10-31'
and bk.IsDeleted = 0
group by Convert(nvarchar(10),bk.BookingDate,103)
order by 1
This query works if directly fired on SQL Server prompt and fetches results. 如果直接在SQL Server提示符下触发并获取结果,则此查询有效。 However when I am trying using Entity Framework I am getting
NULL
value. 但是,当我尝试使用实体框架时,我得到的是
NULL
值。
var values = context.Database
.SqlQuery<KeyValuePair<string, int>>(query)
.ToList<KeyValuePair<string, int>>();
I think this is because you're using the KeyValuePair<>
, try creating a simple class like: 我认为这是因为您正在使用
KeyValuePair<>
,请尝试创建一个简单的类,例如:
public class MyResult
{
public DateTime Date { get; set; }
public int TotalCount { get; set; }
}
And add count(*) as TotalCount
to your query. 并将
count(*) as TotalCount
添加到查询中。 And use that as the generic type parameter for your SqlQuery
call. 并将其用作
SqlQuery
调用的通用类型参数。 A key thing to remember is that EF will look for members on the result type with names that match the columns returned from the query. 要记住的关键是,EF将在结果类型中查找名称与查询返回的列匹配的成员。 So as an example, if your query returned a column called "total_count", you would need a property on your class also called "total_count" (with the underscore).
因此,例如,如果您的查询返回了一个名为“ total_count”的列,则您的类上将需要一个属性,也称为“ total_count”(带下划线)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.