12

In C# with VS 2008,I have a query ,In this query i join more than one tables,so i don't know the type , I want to know how to directly run a sql query in linq .

IEnumerable<Type> results = db.ExecuteQuery<TYpe>("sql query")

My above query works fine but I want to avoid type, I want to write

var results = db.ExecuteQuery("sql query");

Is there any way to write it?

Thanks in advance.

4
  • 1
    How is it supposed for linq2sql to detect what class it needs to map the results? Btw, you're still able to use var in the first sample, aren't you? Commented Apr 12, 2011 at 5:00
  • Is it possible to use a stored procedure? The designer will generate a class for each stored procedures return type if so. Commented Apr 12, 2011 at 6:13
  • Give some sample queries. What are you trying to accomplish? Are the return types the same, but just from different tables? Commented Apr 12, 2011 at 6:49
  • You can't run SQL in LINQ. LINQ is a C# language concept. It doesn't run SQL. That said, many ORMs offer options to run raw SQL. How to do that generally isn't hard to find in their documentation. Commented Feb 16, 2020 at 14:40

2 Answers 2

12
    var result = dataContext.ExecuteQuery<JobsDto>
                 ("Select JobID,JobName From jobs");

but make sure JobsDto has two properties JobID and JobName and there types the same type as the table columns

PS. DTO stand for Data Transfer Object

Sign up to request clarification or add additional context in comments.

2 Comments

Note: If you just need a quick test, you can also make the properties dynamic like so: public class JobsDto { public dynamic JobsID; public dynamic JobName; }, and use a tool like LinqPad to dump the result. Assign them the default value null to avoid warnings and use result type IEnumerable<JobsDto>.
In my case, I needed to select aggregated values. Create a new class model "dto", as suggested. But had to alter a bit. dbContext.Database.SqlQuery<AggregatedValuesDto>("SQL statement").SingleOrDefault();
5

You need to specify the type to map to from the query results. You can use a System.Type object instead of statically specifying it as a generic type parameter:

var results = db.ExecuteQuery(typeof(Customer), "sql query ");

If you just want a plain ADO.NET DataReader you could use the DataContext.Connection property:

using (var cmd = db.Connection.CreateCommand()) 
{ 
  cmd.CommandText = "sql query ";
  var results = cmd.ExecuteReader();
}

3 Comments

Correct, but the question was about Linq. You cannot use the results directly in Linq.
@Matt: The question was about the LINQ-to-SQL API, not the language query feature.
Ok, I agree. However, I prefer the Generic notation.

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.