我试图在EF 6中执行一个SQL查询。select查询返回两个字符串列,例如select 'a', 'b',并且可以有任意数量的行。
我想把结果映射到字典上,但我无法掌握下面的错误。
错误1不能隐式地将'System.Data.Entity.Infrastructure.DbRawSqlQuery>‘类型转换为“System.Collections.Generic.Dictionary”
这是代码:
using (var db = new EFDbContext())
{
Dictionary<string, string> perms = new Dictionary<string, string>();
perms = db.Database.SqlQuery<Dictionary<string, string>>(TheQuery);
}在查询之后,我尝试了各种select和ToDictionary,但它们都没有工作。
发布于 2015-06-11 04:49:40
如果对象具有默认构造函数和属性设置器,则可以使用SqlQuery直接填充对象。然后,可以使用结果创建字典。例如:
public class QueryResult
{
public string A { get; set; }
public string B { get; set; }
}// the colulmn/alias names need to match property names
string query = "SELECT column1 AS [A], column2 AS [B] FROM ..."
using (var db = new EFDbContext())
{
var perms = db.Database.SqlQuery<QueryResult>(query)
.ToDictionary(r => r.A, r => r.B);
}发布于 2015-06-11 04:41:01
您是否试图创建一个具有键值对的字典,该键值对对应于通过查询返回的两个列中的相应值?
如果是这样的话,最好为您提供两次查询服务,并创建两个字符串列表并使用它们创建一个字典。
List<string> keys = new List<string>();
List<string> values = new List<string>();
//Populate Lists with data from LINQ db call
Dictionary<string, string> dict = keys.ToDictionary(x => x, x => values[keys.IndexOf(x)]);这要求列表的大小与您指定的列相同,因为键具有唯一的值。
发布于 2018-09-11 21:37:16
使用泛型改进Jjj's answer:
创建一个通用字典查询结果:
public class DictionaryResult<K,V>
{
public K Key { get; set; }
public V Value { get; set; }
}用法:
const string query = "select id as Key, name as Value from anywhere";
var resultado = context.Database.SqlQuery<DictionaryResult<int, string>>(query);https://stackoverflow.com/questions/30771552
复制相似问题