I am trying to execute the following query
SELECT object_id
FROM sys.tables
WHERE sys.tables.name = 'Projects'
as
int n = context.Database.SqlQuery<int>(
"SELECT object_id from sys.tables where sys.tables.name = 'Projects'")
.FirstOrDefault();
I get n as always 0
If I use SqlConnection
and query it using a SqlCommand
I get the correct results. So why does DbContext.Database.Connection
not let me execute a plain SQL query?
For simplicity I have removed SqlParameter
, so I am aware this code is not SQL Injection safe.
Step 1 − Create a new Console Application project. Step 2 − Right-click on project in solution explorer and select Add → New Item. Step 3 − Select ADO.NET Entity Data Model from the middle pane and enter name ViewModel in the Name field. Step 4 − Click Add button which will launch the Entity Data Model Wizard dialog.
With EF Core 5, we can introduce views in our DbContext and track the evolution of our views using the built-in database migration mechanism. Models behave as they would when mapped directly to a table to take advantage of default mapping conventions.
The DbContext class has a method called OnModelCreating that takes an instance of ModelBuilder as a parameter. This method is called by the framework when your context is first created to build the model and its mappings in memory.
There is no problem with system views, Entity Framework cannot read value types in SqlQuery. So I had to change it,
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();
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