我有一个查询(简单SELECT
语句),它返回Id和Name Id is int
和Name is string
。查询在SSMS中返回结果。我试图在我的MVC应用程序中使用EF获取该记录。如果我创建自定义类而不是使用dictionary
,我可以获得该值。第二个选项不会抛出任何错误,但它会带有零记录。
如何在不创建自定义类的情况下读取值?
C#逻辑:
// 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查询:
SELECT UnitNumber,
UnitName
FROM dbo.MyTable
WHERE Id = 1
AND ScriptId = 10
SQL输出:
UnitNumber UnitName
----------- -----------
9 Universal
答案 0 :(得分:2)
您需要将结果集投影到字典中,如下所示:
var result = context.Database.SqlQuery<MyClass>(sql, callCenterId, id)
.ToDictionary(o => o.UnitNumber, o => o.UnitName);
或
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);