Entity Framework SQL query does not return results

I am using the first Entity Framework database model and am having problems querying my database.

I am 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 the DEPARTMENTs table results table in the debug log, but for some reason the SQL query just returns me "SELECT DESCRIPTION FROM DEPARTMENT WHERE DEPARTMENT =" FINANCE "in the console instead of executing the query, does anyone know why?

Greetings

+3
source share
3 answers

To execute the query to the provider, you should use any extension obtained from the IEnumerableie ToList()or First()orFirstOrDefault()

. ? ? , ?

, :

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

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

( ):

var description = ctx.DEPARTMENTs.Where(s=>s.Department.ToUpper() =="FINANCE")
                     .Select(s=>s.Description)
                     .FirstOrDefault();
+5

Try:

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

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

, , LINQ, , . ToList.

System.Diagnostics.Debug.WriteLine(Object) ToString Listeners. Debug.WriteLine()

+3

SqlQuery DbSqlQuery<TEntity>. , , DbSqlQuery<DEPARTMENTs>.

SQL- , System.Data.Entity.DbContext . System.Data.Entity.DbSet . , ; , , , foreach. SQL- - System.Data.Entity.DbContext.Database. System.Data.Entity.Infrastructure.DbSqlQuery .

, ; , , , foreach.

, , .

+1

All Articles