0

I have a question about getting data from a database using a raw SQL query:

DataContext.Database.SqlQuery<string>(runQuery).FirstOrDefault();

The question is, how to convert all returned values to a String, or how to handle different returned data types using Database.SqlQuery

3
  • You could have them come back as object and ToString() them. It's a little unclear as to what you're trying to achieve. Commented Jun 14, 2016 at 14:13
  • I'm trying to create a .net function that will send raw sql queries to the DB and will receive back requested data (returned data could be with different data types) Commented Jun 14, 2016 at 14:20
  • Have you looked into Stored Procedures? Commented Jun 14, 2016 at 14:21

1 Answer 1

2

You are going to need to create a class and map the columns that returns your query with primitive data type properties declared in that class,eg:

// SQL version of the above LINQ code.
string query = "SELECT EnrollmentDate, COUNT(*) AS StudentCount "
        + "FROM Person "
        + "WHERE Discriminator = 'Student' "
        + "GROUP BY EnrollmentDate";
IEnumerable<EnrollmentDateGroup> data = db.Database.SqlQuery<EnrollmentDateGroup>(query);

And your class would be something like this:

public class EnrollmentDateGroup
{
  public int StudentCount {get;set;}
  public DateTime EnrollmentDate {get;set;}
}

You can find the list of primitive data types you can use to map Microsoft SQL Server data types in this link

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

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.