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'
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With