Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to read system views in Entity Framework

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.

like image 947
Akash Kava Avatar asked Jan 27 '16 11:01

Akash Kava


People also ask

How do I access view in Entity Framework?

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.

Does EF core support views?

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.

What is OnModelCreating in Entity Framework?

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.


1 Answers

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();
like image 110
Akash Kava Avatar answered Sep 19 '22 08:09

Akash Kava