简体   繁体   中英

Using SqlQuery<Dictionary<string, string>> in Entity Framework 6

I'm trying to execute a SQL query in EF 6. The select query returns two string columns, eg select 'a', 'b' , and can have any number of rows.

I'd like to map the result to a dictionary, but I can't get ride of the following error.

Error 1 Cannot implicitly convert type 'System.Data.Entity.Infrastructure.DbRawSqlQuery>' to 'System.Collections.Generic.Dictionary'

This is the code:

using (var db = new EFDbContext())
{
    Dictionary<string, string> perms = new Dictionary<string, string>();
    perms = db.Database.SqlQuery<Dictionary<string, string>>(TheQuery);
}

I've tried various select and ToDictionary after the query, but none of them worked.

You can use SqlQuery to directly populate an object if the object has a default constructor and property setters. The result can then be used to create a dictionary. For example:

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

Are you trying to create a Dictionary with Key-Value pairings corresponding to the respective values in the two columns returned via your query?

If so you would be best served querying twice, and create two Lists of strings and creating a Dictionary using those.

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

This requires that the Lists are of the same size and column you designate as keys holds unique values.

Improving the Jjj's answer with generics:

create a generic Dictionary query result:

public class DictionaryResult<K,V>
{
    public K Key { get; set; }
    public V Value { get; set; }
}

Usage:

const string query = "select id as Key, name as Value from anywhere";
var resultado = context.Database.SqlQuery<DictionaryResult<int, string>>(query);

I need to return a list of KeyValuePair from a parametered SQL call to Entity Framework. I built my code based on the previous posts. By having a generic dictionaryResult, you can reuse it to return a list of generic keyvaluePair from any query that has Key Value columns. Here it is if it's useful to anyone:

  1. a generic class:
    private class DictionaryResult<K, V>
        {
            public K Key { get; set; }
            public V Value { get; set; }
        }
  1. define your SQL:
private const string SQL = "select Acct_No as Key, XX as Value from XXXXX where acct_no in ( :accts)";
  1. use the generic class to return a list of 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;
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM