Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework SQL query not returning results

I am using an Entity Framework Database first model and I am having problems querying my DB.

I'm trying to use the following code:

var ctx = new dbEntities();
var description = ctx.DEPARTMENTs.SqlQuery("SELECT DESCRIPTION FROM DEPARTMENT WHERE DEPARTMENT='FINANCE'");
System.Diagnostics.Debug.WriteLine(description);

I can see my table of results for the DEPARTMENTs table in the debug log, but for some reason the SQL query is just returning me this in the console rather than executing the query, anybody know why?

SELECT DESCRIPTION FROM DEPARTMENT WHERE DEPARTMENT='FINANCE'
like image 908
MattTheHack Avatar asked Feb 26 '14 09:02

MattTheHack


Video Answer


1 Answers

To make the query execute against the provider, you have to use any extension derived from IEnumerable i.e. ToList() or First() or FirstOrDefault()

Now you have to consider few things. What your query might possibly return? A List of data or a single data? Or even if a list of matches found, you want just the single one?

from the syntax of your query I assume you should be doing this:

var ctx = new dbEntities();
var dep = ctx.DEPARTMENTs
             .SqlQuery("SELECT * FROM DEPARTMENT WHERE DEPARTMENT='FINANCE'")
             .FirstOrDefault();

if(dep!=null)
{
    var description = department.Description;
}

Alternatively, you can also do this(I would prefer):

var description = ctx.DEPARTMENTs.Where(s=>s.Department.ToUpper() =="FINANCE")
                     .Select(s=>s.Description)
                     .FirstOrDefault();
like image 58
Manish Mishra Avatar answered Sep 18 '22 01:09

Manish Mishra