22

I have to select multiple columns from a database and I don't have a matching entity. so my query looks like this:

var result = _dbContext.Database.SqlQuery<List<string>>(
             "select ID, NAME, DB_FIELD from eis_hierarchy");

I am getting the result set, each row contains list of strings but count is 0.

So how do I select multiple columns using Database.SqlQuery?

0

2 Answers 2

50

You have to capture the results into a class with matching property names, and (at least) a parameterless constructor:

class DbResult
{
    public int ID { get; set; }
    public string NAME { get; set; }
    public string DB_FIELD { get; set; }
}

var result = _dbContext.Database.SqlQuery<DbResult>(
                 "select ID, NAME, DB_FIELD from eis_hierarchy");
Sign up to request clarification or add additional context in comments.

2 Comments

I found this to work well--except when the SP result field has a name like "unallocated space", which obviously can't be used as a .NET property name. Anyone have an idea what to do in that case?
Probably use an alias: select [unallocated space] AS unallocated_space from Table.
0

Using C# version higher than 6, it can be written in this way as well:

var result = _dbContext.Database.
                SqlQuery<(int ID, string NAME, string DB_FIELD)>("select ID, NAME, DB_FIELD from eis_hierarchy");

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.