3

I have this segment of code selecting one column from a table which works fine:

db.Database.SqlQuery<string>("select Col1 from ....).ToList();

However, as expected when trying to select more than one column it errors as the result structure is incorrect.

I've tried the following:

db.Database.SqlQuery<Tuple<string, string>>("select Col1, Col2 from ...).ToList();

Which returns the error:

The result type 'System.Tuple`2[System.String,System.String]' may not be abstract and must include a default constructor.

How can I fix this, Am I correct to be using Tuple?

2
  • 1
    How about using a class (with the properties you select in the query) instead of Tuple? Commented Jan 12, 2017 at 12:44
  • try string[] just a guess.... dont think it would work... class is much better Commented Jan 12, 2017 at 12:45

2 Answers 2

3

Define a class for your query result e.g.

class QueryResult
{
    public string Col1 { get; set; }
    public string Col2 { get; set; }
}

and query like this:

db.Database.SqlQuery<QueryResult>("select Col1, Col2 from ...).ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This has resolved my issue.
3

You need to have a class that contains properties that have the same name of your columns in order for Database.SqlQuery to work. See here.

public class MyType
{
    public string Col1 { get; set; }
    public string Col2 { get; set; }
}

List<MyType> list = db.Database.SqlQuery<MyType>("select Col1, Col2 from ....").ToList();

1 Comment

Yeah, I think the more important thing is you have to make sure the properties have the same name with your query columns.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.