2016-01-27 6 views
6

Sto cercando di eseguire la query seguenteImpossibile leggere viste di sistema in Entity Framework

SELECT object_id 
    FROM sys.tables 
    WHERE sys.tables.name = 'Projects' 

come

int n = context.Database.SqlQuery<int>(
     "SELECT object_id from sys.tables where sys.tables.name = 'Projects'") 
     .FirstOrDefault(); 

ottengo n come sempre 0

Se uso SqlConnection e interrogazione usando un SqlCommand ottengo i risultati corretti. Quindi, perché DbContext.Database.Connection non mi consente di eseguire una semplice query SQL?

Per semplicità ho rimosso SqlParameter, quindi sono consapevole che questo codice non è sicuro per SQL Injection.

+0

Penso che il nome della tabella non esista. Se eseguo la query (dopo aver cambiato il nome in qualcosa di valido) funziona bene –

risposta

0

penso che il risultato di Database.SqlQuery deve essere prima convertito alla lista:

Prova questa:

int n = context.Database.SqlQuery<int>(
    "SELECT object_id from sys.tables where sys.tables.name = 'Projects'") 
    .ToList().FirstOrDefault(); 
+1

No, non dovrebbe. Dalla documentazione 'Nota che, proprio come per le query LINQ, la query non viene eseguita fino a quando i risultati non vengono enumerati', chiamando' FirstOrDefault() 'enumera anche la query –

1

Non c'è nessun problema con viste di sistema, Entity Framework non può leggere i tipi di valore in sqlquery. Quindi ho dovuto cambiarlo,

public class SingleValue<T>{ 
    public T Value {get;set;} 
} 

int n = context.Database.SqlQuery<SingleValue<int>>(
    "SELECT object_id as Value from sys.tables where sys.tables.name = 'Projects'") 
    .ToList().Select(x=>x.Value).FirstOrDefault();