Casting Problem : (casting Entity Data Model primitive types)


  • I have the follwoing Code :

    public IQueryable<IWorkItems> GetWorkItems()


    ObjectQuery<WorkItems> allWorkItems = context.WorkItems;

    LogHelper.GetLogger().Info("This is a test message");

    IQueryable<MoICT.ESB.WFE.Data.Model.WorkItem> temp = from workItem in allWorkItems

    select new MoICT.ESB.WFE.Data.Model.WorkItem


    ID = workItem.ID,

    ActionName = workItem.ActionName,

    URL = workItem.Url,

    IsDeleted = (bool)workItem.IsDeleted,

    ServiceID = (int)workItem.Services.ID,

    RoleID = (int)workItem.Roles.ID,


    return temp.Cast<IWorkItems>();



    when executed, the cating ( temp.Cast<IWorkItems>() ) throws:

     "System.NotSupportedException: Unable to cast the type 'MoICT.ESB.WFE.Data.Model.WorkItem' to type 'MoICT.ESB.WFE.Common.Interfaces.Data.Model.IWorkItems'. LINQ to Entities only supports casting Entity Data Model primitive types"

    may any one help ?

    Wednesday, November 19, 2008 8:31 AM


All replies


    Hi Bilal,


    Since your Temp data is IQueryable, EF will try to apply cast operation on the database and it wont work because cast operator only works with scalar types unlike linq to sql in which cast operator works but it give in correct results. You can do this




    you can you also use OfType if you want to only return derived types.  here are few blog postings on cast that i did while back.




    Zeeshan hirani

    Wednesday, November 19, 2008 6:47 PM
  • Thank you Zeeshan for your response,


    Yes, Unfortunately EF doesn’t support casting within user defined types (See


    Regarding OfType method it is not useful in my case since the retrieved items has the same data type.


    It seems that the only solution (which is not satisfied for me) is to get IEnumerable object instead of IQueryable by using ToList() method and then cast to IWorkItems.

    Thursday, November 20, 2008 11:24 AM
  • hello Bilal Al-Smadi

    i faced the same problem .



    i faced the same exception when i used the following method .

    //Method 1


    public ObjectQuery<E> DoQuery(Expression<Func<E, object>> sortExpression)



    if (null == sortExpression)



    return DoQuery();



    return (ObjectQuery<E>)DoQuery().OrderBy<E, object>(sortExpression);



    //the DoQuery



    ObjectQuery<E> DoQuery()



    return _context.CreateQuery<E>("[" + typeof(E).Name + "]");


    the solution was 
    instead of Expression<Func<E, object>> sortExpression  i used



    <Func<E, T>> sortExpression.

    then i changed the Method1 to


    public ObjectQuery<E> DoQuery<T>(Expression<Func<E, T>> sortExpression)



    if (null == sortExpression)



    return DoQuery();



    return (ObjectQuery<E>)DoQuery().OrderBy<E, T>(sortExpression);




    Friday, December 18, 2009 8:41 PM