1

My C# VS2015 application throws this exception:

System.InvalidCastException was unhandled

Message=Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[ADONET4LINQtoENTITIES.Customer]' to type 'System.Data.Objects.ObjectQuery'.
Source=ADONET4LINQtoENTITIES

The error occurs in the line that defines the query variable:

var customers = from c in de.Customers
                where c.Orders.Any(o => o.OrderAmount > 150)
                select c;
 
string query = ((ObjectQuery)customers).ToTraceString();

My assumption is that ObjectQuery is prompting the exception.

I tried string query = ((DbQuery)customers).ToString() instead, which works in VS2013, but this resulted in the same exception.

Why does VS2015 throw exceptions with these query approaches?

Community
  • 1
  • 1
Spencer H
  • 653
  • 3
  • 12
  • 30
  • 3
    The error message says it all: `customers` is of type `DbQuery`, not `DbQuery` nor `ObjectQuery`. – manji Jul 23 '15 at 21:37
  • Are you using the same version of EF when it worked and when it didn't? [It seems they're not related anymore.](http://stackoverflow.com/questions/4766122/how-can-i-convert-a-dbqueryt-to-an-objectqueryt) – Jeff Mercado Jul 25 '15 at 01:44
  • @manji that implementation worked like charm. I just had to add: `using System.Data.Entity.Infrastructure`, and adjust `ToTraceString()` to `ToString()` in the `query` definition. – Spencer H Jul 30 '15 at 15:14

1 Answers1

2

Because Customers is not an ObjectQuery what you want is an ObjectQuery<Customer> so remove the projection as well (the Select).

Change to

var CustomersQuery= from c in de.Customers
                    where c.Orders.Any(o => o.OrderAmount > 150);

string query =  CustomersQuery.ToTraceString();

I took out the naming lexical ambiguity by naming it CustomersQuery.

See ObjectQuery.ToTraceString Method (System.Data.Objects) for more information.

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122