簡體   English   中英

使用 SqlQuery <Dictionary<string, string> &gt; 在實體框架 6 中

[英]Using SqlQuery<Dictionary<string, string>> in Entity Framework 6

我正在嘗試在 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 ,但都沒有奏效。

如果對象具有默認構造函數和屬性設置器,則可以使用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);
}

您是否正在嘗試創建一個帶有鍵值對的字典,該鍵值對對應於通過查詢返回的兩列中的相應值?

如果是這樣,您最好進行兩次查詢,並創建兩個字符串列表並使用它們創建一個字典。

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

這要求列表具有相同的大小,並且您指定為鍵的列包含唯一值。

用泛型改進Jjj 的答案

創建一個通用的 Dictionary 查詢結果:

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

我需要從對實體框架的參數化 SQL 調用返回 KeyValuePair 列表。 我根據以前的帖子構建了我的代碼。 通過擁有通用字典結果,您可以重用它從具有鍵值列的任何查詢返回通用 keyvaluePair 列表。 如果它對任何人有用,這里是:

  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. 使用泛型類返回鍵值對列表:
    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;
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM