Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Constructor Error [duplicate]

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?

like image 802
Cory Avatar asked Jun 01 '26 08:06

Cory


2 Answers

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();

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();
like image 37
Ghasan غسان Avatar answered Jun 02 '26 21:06

Ghasan غسان



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!