1

I have a page where the user can input a SQL query. This query can be against any table in my database. I need to execute this query against the corresponding table and show the result in my view. How to do this?

For eg: user can input Select * from ABC or select max(price) from items.

I tried:

var results = DbContext.Database.SqlQuery<string>(query).ToList();

But this throws an error:

The data reader has more than one field. Multiple fields are not valid for EDM primitive or enumeration types.

Whatever the result I should be able to pass it to the view and display it.

Please help.

3
  • var blogs = context.YourModel.SqlQuery("SELECT * FROM dbo.YourTable").ToList(); Commented Sep 22, 2016 at 11:36
  • I cannot specify 'myModel' because I am not aware of what the user might input as the query. So whatever be the model I need to get it executed. Commented Sep 22, 2016 at 11:40
  • 2
    Letting users execute any SQL directly against the db is probably a very bad idea by the way. Commented Sep 22, 2016 at 12:55

2 Answers 2

1

The error message states the problem exactly:

The data reader has more than one field. Multiple fields are not valid for EDM primitive or enumeration types.

To correct the problem, you can either submit a SQL string that returns a single string column from the database, or supply a type parameter that allows EF to map multiple columns.

For example:

SELECT someStringColumn FROM ABC

OR

var results = DbContext.Database.SqlQuery<MyDto>(query).ToList();

Where MyDTO looks something like this:

class MyDto
{
    public int AddressID { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
}
Sign up to request clarification or add additional context in comments.

Comments

0

you can use

 SqlQuery<dynamic>" 

this will resolve the error but you will only be able to get the count of the result returned. So you can just verify the query has returned some data. But still will need to know the type of the returned data.

It is a risk of providing the user to input query to database.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.