如何在Entity Framework中读取具有不同数据类型的值?

时间:2018-05-08 20:21:26

标签: c# sql-server entity-framework

我有一个查询(简单SELECT语句),它返回Id和Name Id is intName 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 

1 个答案:

答案 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);