Method cannot be translated into a store expression syntax error

c# entity-framework linq linq-to-entities linq-to-objects

Question

I'm using LINQ to Entity and getting error

Method cannot be translated into a store expression

var myStrings = from keys in keyTable
                                       join values in valuesTable
                                           on keys.ID equals values.FK_TableKey
                                       select new NewModel
                                       {
                                           Value = values.Value,                                        
                                           Hash = CalculateHash(string.Format("{0}_{1}", keys.Key, keys.Context))
                                       };

//I tried to convert in into LINQ syntax like below

//How to calculate Hash value which will work on LINQ to Entity?

//Method

 public string CalculateHash(string input)
        {
            if (input == null)
                return null;
//calculate MD5 hash
            var md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
            byte[] hash = md5.ComputeHash(inputBytes); 

            var sb = new StringBuilder();
            foreach (byte t in hash)
                sb.Append(t.ToString("P2"));

            return sb.ToString();
        }
1
6
3/9/2015 12:27:05 PM

Accepted Answer

Since hash value should be computed on the .NET side, you can add AsEnumerable() call after the portion that produces the "raw data", and then compute the rest outside your RDBMS, like this:

var rawStrings = from keys in keyTable
                join values in valuesTable
                on keys.ID equals values.FK_TableKey
                select new {
                    Value = values.Value,                                        
                    keys.Key,
                    keys.Context
                };
var myStrings = rawStrings.AsEnumerable().Select(t => new NewModel {
     Value = t.Value,
     Hash = CalculateHash(string.Format("{0}_{1}", t.Key, t.Context))
});

The first query runs on the RDBMS side, and produces the key and the context for computing the Hash. The second query uses the raw data to compute the desired output.

8
3/9/2015 4:30:54 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow