0

I am creating a WPF app using C#, Entity Framework and SQL Server 2008 R2. 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. However when I am trying using Entity Framework I am getting NULL value.

var values = context.Database
    .SqlQuery<KeyValuePair<string, int>>(query)
    .ToList<KeyValuePair<string, int>>();

enter image description here

  1. Is it because I am using a KeyValue pair in the method call?
  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?
3
  • why are you alternating using BookingDate as a string and date? If it's stored as a date in your database, select it and compare it as a date Commented Oct 27, 2014 at 16:27
  • Just a hint in case you are not aware: EntityFramework works best with LinQ and NOT writing plain Text SQL-Queries. Commented Oct 27, 2014 at 16:29
  • @Kritner: in database its datetime. I want count by date. So need to erase the time part Commented Oct 27, 2014 at 16:30

1 Answer 1

2

I think this is because you're using the KeyValuePair<>, try creating a simple class like:

public class MyResult
{
    public DateTime Date { get; set; }
    public int TotalCount { get; set; }
}

And add count(*) as TotalCount to your query. And use that as the generic type parameter for your SqlQuery call. 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. 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).

Sign up to request clarification or add additional context in comments.

1 Comment

Its worth a try!! Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.