1 Reply Latest reply on Jan 3, 2013 9:27 PM by 977106

    How to rewrite query using Entity Framework to work against an Oracle db

      Given the schema in seen in this Stackoverflow post [http://stackoverflow.com/questions/14126458/return-objects-missing-records-in-many-to-many-using-ef-5-0] , I'm trying to build an EF query that returns Contacts that are missing required Forms. Each Contact has a ContactType that is related to a collection of FormTypes. Every Contact is required to have at lease one Form (in ContactForm) of the FormTypes related to its ContactType.

      The query that EF generates from the linq query below works against Sql Server, but not against Oracle.

      var query = ctx.Contacts.Where (c => c.ContactType.FormTypes.Select (ft => ft.FormTypeID).Except(c => c.Forms.Select(f => f.FormTypeID)).Any());

      I'm in the process of refactoring a data layer so that all of the EF queries that work against Sql Server will also work against Oracle using Devart's dotConnect data provider.

      The error that Oracle is throwing is ORA-00904: "Extent1"."ContactID": invalid identifier.

      The problem is that Oracle apparently doesn't support referencing a table column from a query in a nested subquery of level 2 and deeper. The line that Oracle throws on is in the Except (or minus) sub query that is referencing "Extent1"."ContactID". "Extent1" is the alias for Contact that is defined at the top level of the query. Here is Devart's explanation of the Oracle limitation. [http://www.devart.com/dotconnect/oracle/faq.html#q56]

      The way that I've resolved this issue for many queries is by re-writing them to move relationships between tables out of the Where() predicate into the main body of the query using SelectMany() and in some cases Join(). This tends to flatten the query being sent to the database server and minimizes or eliminates the sub queries produced by EF. Here is a similar issue solved using a left outer join.[http://stackoverflow.com/questions/14047129/how-to-query-a-many-to-many-for-the-absence-of-records-using-ef5]

      The column "Extent1"."ContactID" exists and the naming syntax of the query that EF and Devart produce is not the issue.

      Any ideas on how to re-write this query will be much appreciated. The objective is a query that returns Contacts missing Forms of a FormType required by the Contact's ContactType that works against Oracle and Sql Server.

      Edited by: cResults on Jan 2, 2013 1:59 PM