18

I use Asp.Net 4 and C#, I use EF 4.

I have this query, I receive an error:

 An expression tree may not contain a dynamic operation

dynamic o = e.Item.DataItem;
var imagesContent = context.CmsImagesContents.FirstOrDefault(img => img.ContentId == o.ContentId);

It seems is imposible to Cast a Dynamic Type using a Lamba Expression.

How I can fix the problem, and able to use my object o in my Lamba? Thanks

PS: e.Item.DataItem is of Type CmsContent and o.ContentId is of type Int

GibboK
  • 71,848
  • 143
  • 435
  • 658

3 Answers3

16

Unboxing the object will do the trick:

     int contentId = (int)o.ContentId;
     var image = context.CmsImagesContents.FirstOrDefault(img => img.ContentId == contentId);

For more info about 'boxing/unboxing' click here

Jeric Cruz
  • 1,899
  • 1
  • 14
  • 29
GibboK
  • 71,848
  • 143
  • 435
  • 658
4

Change

dynamic o = e.Item.DataItem;

To

var o = (CmsContent)e.Item.DataItem;
cdhowie
  • 158,093
  • 24
  • 286
  • 300
0

I was seeing this issue in code that was not using dynamics in any obvious way. I found it was caused by the inclusion of the below reference in the class using statements. Removing it seemed to change the way the the compiler interpreted the Linq expression.

using System.Linq.Dynamic.Core;
gbro3n
  • 6,729
  • 9
  • 59
  • 100