MVC Entity Framework Random SQL Queries that don't map to db objects and may return multiple datasets.

Bryan Valencia 181 Reputation points
2023-07-01T04:39:36.7366667+00:00

ASP.NET (NOT CORE) MVC

  1. I'm storing a list of random queries in a table.
  2. NONE of the queries match any database object, like Customers, Orders, etc.
  3. Some queries may return more than one dataset.
  4. Some may be update or delete queries

I need to execute ANY random query with any number of parameters, and return the results in a page.

so this might be a query...

select Firstname, lastName from customers where State=@state

or this...

select T.ID, T.Transactiondate, T.amount, C.FullName, C.City, C.State
from transactions T
join customers C on C.ID=T.CustomerID
where
T.transactionDate between @d1 and @d2

or this (multiple answers)

select * from customers;
select * from orders;

So the code I've seen so far won't compile, as this...

			List<string> parms = Common.ExtractSQLParams(query.SQL);
			List<object> paramset = new List<object>();
			foreach (string parm in parms)
			{
				string paramname = string.Format("@{0}", parm);
				string paramval = Request.Form[parm];
				paramset.Add(new SqlParameter(paramname, (object)paramval));
			}
			DbSqlQuery qry = db.Database.SqlQuery(query.SQL, paramset.ToArray());  // ERROR HERE

gives

Error CS1503 Argument 1: cannot convert from 'string' to 'System.Type' Error CS1503 Argument 2: cannot convert from 'object[]' to 'string'

I know I could do something like this with SQLDataReader, but with EF? Can this be done?

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,395 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,269 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 26,136 Reputation points
    2023-07-01T12:12:55.8833333+00:00

    I know I could do something like this with SQLDataReader, but with EF?

    EF/LINQ does not populate multiple separate objects. It will populate navigation properties though.

    Just use ADO.NET since you already know how to handle this in ADO.NET.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,686 Reputation points
    2023-07-01T18:47:14.5266667+00:00

    the goal of EF was to return strongly typed objects from queries. if you want dynamic query results use a DataTable or DataReader via adodb.

    1 person found this answer helpful.
    0 comments No comments