Reputation: 11366
i am making the transition from LINQ2SQL
to EF and am having some trouble with some basic lambda expressions.
In the following example, I am trying to retrieve a basic list of client related data. This statement when run using a LINQ2SQL
data context works fine.
var data = db.Clients.Select(c => c.Id + ":" + c.Firstname);
foreach (var item in data)
{
}
When i execute it against an EF data context i get:
NotSupportedException - Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.
NB
: the Id field is an integer.
I have been able to fix the error by adding a ToArray()
after db.Clients.
Can someone please explain if..
a) I need to make this kind of code change to every pre-exisitng statement in my solution to get it working with EF; and
b) Why does EF have so much trouble with a basic concatenation when LINQ2SQL
was fine?
thanks.
Upvotes: 0
Views: 112
Reputation: 149050
I can't tell you why it works in Linq2SQL and not in Entity Framework, but I can help you solve your issue.
I suggest you use the SqlFunctions.StringConvert
function.
var data = db.Clients.Select(c =>
SqlFunctions.StringConvert((double)c.Id) + ":" + c.Firstname);
Personally, if I have to do any string manipulation, I try to place that only in my client code, like this:
var data = db.Clients.Select(c => { c.Id, c.Firstname });
foreach (var item in data)
{
var stringData = String.Format("{0}:{1}", item.Id, item.Firstname);
...
}
Upvotes: 0