【问题标题】:Using SqlQuery<Dictionary<string, string>> in Entity Framework 6在实体框架 6 中使用 SqlQuery<Dictionary<string, string>>
【发布时间】:2015-06-11 04:24:37
【问题描述】:

我正在尝试在 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);
}

查询后我尝试了各种selectToDictionary,但都没有成功。

【问题讨论】:

    标签: c# sql .net entity-framework dictionary


    【解决方案1】:

    如果对象具有默认构造函数和属性设置器,您可以使用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);
    }
    

    【讨论】:

    • 我不能使用SqlQuery&lt;dictionary...&gt;吗?如果我能避免额外的课程,那就太好了。
    • 嗯,SqlQuery 的返回类型是 DbSqlQuery,它已经是一个集合(或者从技术上讲是一个 IEnumerable),我认为你不会想要一个字典的集合。如果您已经有一个适合查询的现有类,那也可以。不幸的是,TupleKeyValuePair 不起作用,因为它们没有默认构造函数。
    • 我个人认为,如果你要在多个地方使用这些数据,我认为额外的类应该不是问题。
    • 非常感谢 jjj。这是一个扩展方法,会更新一些对象的字段,字段的名称和查询的第一列是一样的。但是这些字段是bool,并且基于第二列,我将决定它们中的每一个都应该是false,或者true。我可以使用类本身来更新字段(不丢失其他字段)吗?
    • 抱歉,我不确定我是否理解您在此询问的内容。听起来您可以使用根据第二列的值返回布尔值的自定义属性获取器?
    【解决方案2】:

    您是否尝试创建一个字典,其键值对对应于通过查询返回的两列中的相应值?

    如果是这样,您最好查询两次,然后创建两个字符串列表并使用它们创建字典。

    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)]);
    

    这要求列表具有相同的大小,并且您指定为键的列包含唯一值。

    【讨论】:

      【解决方案3】:

      使用泛型改进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);
      

      【讨论】:

        【解决方案4】:

        我需要从对实体框架的参数化 SQL 调用返回 KeyValuePair 列表。我根据之前的帖子构建了我的代码。通过使用通用 dictionaryResult,您可以重用它以从任何具有键值列的查询中返回通用键值对列表。如果它对任何人有用,就在这里:

        1. 一个泛型类:
            private class DictionaryResult<K, V>
                {
                    public K Key { get; set; }
                    public V Value { get; set; }
                }
        
        1. 定义您的 SQL:
        private const string SQL = "select Acct_No as Key, XX as Value from XXXXX where acct_no in ( :accts)";
        
        1. 使用泛型类返回keyvalueapair列表:
            public List<KeyValuePair<int, string>> GetXXX(string accts)
                {
                    using (var securityEntities = ODPFactory.GetSecurityEntities(_ownerRef))
                    {
                        var returnValue = securityEntities.ExecuteStoreQuery<DictionaryResult<int, string>>(SQL, new object[] { accts })
                            .Select(item => new KeyValuePair<int, string>(item.Key, item.Value))
                            .ToList();
                        return returnValue;
                    }
                }
        

        【讨论】:

          猜你喜欢
          • 2012-03-01
          • 2013-10-18
          • 1970-01-01
          • 1970-01-01
          • 2012-09-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-13
          相关资源
          最近更新 更多