简体   繁体   English

实体框架数据库查询结果为NULL值

[英]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>>();

在此处输入图片说明

  1. Is it because I am using a KeyValue pair in the method call? 是因为我在方法调用中使用了KeyValue对吗?
  2. Is there any alternative of doing this using Entity Framework? 使用实体框架还有其他选择吗?
  3. Or should I use old style database connection and command to run this query? 还是应该使用旧式数据库连接和命令来运行此查询?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM