2

I am trying to fetch a column value and convert it as a list of formatted string value and I tried the below code

List<string> _names = (from p in context.RakHolders select string.Format("{0},{1}", p.Name.Split(',')[0].Trim(), p.Name.Split(',')[1].Trim())) .ToList(); 

My intention is to get a list of names with no unwanted space between commas in the column Name

I am getting exception while executing this line as

An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

Additional information: LINQ to Entities does not recognize the method
'System.String Format(System.String, System.Object, System.Object)' method, and this method cannot be translated into a store expression.

How can I make this work [get a list of formatted column values] with LINQ

2
  • Because it couldn't be translated to T-SQL, Linq to Entities couldn't recognize it. Add AsEnumerable() after RakHolders might be helpful. Check this stackoverflow.com/questions/34061637/… Commented Nov 4, 2016 at 8:16
  • Try adding .AsEnumerable() after context.RakHolders Commented Nov 4, 2016 at 8:16

2 Answers 2

3
List<string> _names = (from p in context.RakHolders select p.Name) .ToList() .Select(name => name.Split(',')) .Select(nameSplitted => string.Format("{0},{1}", nameSplitted[0].Trim(), nameSplitted[1].Trim() )) .ToList(); 

Explanation: 'string.Format' cannot be translated to SQL so firstly we need to materialise the list with a first 'ToList()' (here we get the list of names, it's much more efficient than materialising full entities). Having the list in the memory you can transform it to the form you require.

Sign up to request clarification or add additional context in comments.

Comments

1

EF is trying to execute the expression on the SQL-Server. If you fetch the items first, it shouldn't be a problem:

List<string> _names = context.RakHolders .Select(r => r.Name) .ToList() .Select(p => p.Split(',')) .Select(s => string.Format("{0},{1}", s[0].Trim(), s[1].Trim()) .ToList(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.