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
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.