Entity Framework SQL query not returning results

c# entity-framework sql

Question

I am having trouble querying my database while utilizing an Entity Framework Database first model.

I'm attempting to use the code below:

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

My results table for the test is visible.DEPARTMENTs However, for some reason, the SQL query is merely returning me this in the console rather than actually running the query; does anyone know why? table in the debug log.

SELECT DESCRIPTION FROM DEPARTMENT WHERE DEPARTMENT='FINANCE'
1
5
8/13/2018 11:23:41 AM

Accepted Answer

You must use any extension derived from to force the query to run against the provider.IEnumerable i.e. ToList() or First() or FirstOrDefault()

You now need to think about a few things. What results might your search have? A single data or a list of data? Or do you only want the one match, even if a list of matches were found?

I'm assuming that you should be performing this based on the syntax of your query:

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

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

As an alternative, you might also carry out what I would prefer:

var description = ctx.DEPARTMENTs.Where(s=>s.Department.ToUpper() =="FINANCE")
                     .Select(s=>s.Description)
                     .FirstOrDefault();
8
7/10/2015 8:33:56 PM

Popular Answer

Try:

var description = ctx.DEPARTMENTs.SqlQuery<string>("SELECT DESCRIPTION FROM DEPARTMENT WHERE DEPARTMENT='FINANCE'").ToList();

EDIT: Raw SQL http://msdn.microsoft.com/en-us/data/jj592907.aspx queries

The query is not executed until the results are enumerated, as is the case with LINQ queries; in the example given above, this is accomplished through the use of the ToList method.

System.Diagnostics.Debug. The object's ToString method value is written to the trace listeners in the Listeners collection using the WriteLine(Object) method. Debug.WriteLine(Object)



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow