1

I have a query (simple SELECT statement) which returns Id and Name where Id is int and Name is string. The query returns result in SSMS. I am trying to get that record using EF in my MVC application. I can get that value if I create custom class but not of I use dictionary. Second option doesn't throw any error but it comes with zero record.

How can I read the value without creating custom class?

C# Logic:

// Option-1 = Works
var sql = @"SELECT UnitNumber, 
                   UnitName
            FROM dbo.MyTable 
            WHERE Id = @p0
            AND ScriptId = @p1";

var result = context.Database.SqlQuery<MyClass>(sql, callCenterId, id);

public class MyClass
{
    public int UnitNumber { get; set; }
    public string UnitName { get; set; }
}


// Option-2 = Doesn't Work
var sql = @"SELECT UnitNumber, 
                   UnitName
            FROM dbo.MyTable 
            WHERE Id = @p0
            AND ScriptId = @p1";

var result = context.Database.SqlQuery<Dictionary<int, string>>(sql, callCenterId, id);

SQL Query:

SELECT UnitNumber, 
       UnitName
FROM dbo.MyTable 
WHERE Id = 1
AND ScriptId = 10

SQL Output:

UnitNumber  UnitName
----------- -----------
9           Universal 
1
  • 1
    I wouldn't expect option #2 to work. The query is not returning columns that can be converted to a dictionary. Just use a class. Commented May 8, 2018 at 20:23

1 Answer 1

2

You need to project your resultset into a dictionary, like this :

var result = context.Database.SqlQuery<MyClass>(sql, callCenterId, id)
             .ToDictionary(o => o.UnitNumber, o => o.UnitName);

or

var result = context.Database.SqlQuery<MyClass>(sql, callCenterId, id)
         .Select(x=> new KeyValuePair<int, string>(x.UnitNumber, x.UnitName))
         .ToDictionary(x=>x.Key, x=>x.Value);
Sign up to request clarification or add additional context in comments.

1 Comment

This make sense. Thank you.

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.