Question

Given the schema below, 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.

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.

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.

enter image description here

Was it helpful?

Solution

The following entity framework query returns all the ContactIDs for Contacts missing FormTypes required by their ContactType when querying against both Sql Server and Oracle.

var contactNeedsFormTypes = 
       from c in Contacts 
       from ft in c.ContactType.FormTypes
       select new { ft.FormTypeID, c.ContactID};

var contactHasFormTypes = 
       from c in Contacts
       from f in c.Forms
       select new { c.ContactID, f.FormTypeID};

var contactsMissingFormTypes = 
       from n in contactNeedsFormTypes
       join h in contactHasFormTypes
          on new {n.ContactID, n.FormTypeID} equals new {h.ContactID, h.FormTypeID}
              into jointable
              where jointable.Count()==0
select n.ContactID;

contactsMissingFormTypes.Distinct();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top