Filtering FetchEntityCollection based on relationship collection count

Posts   
 
    
Posts: 48
Joined: 26-Mar-2007
# Posted on: 11-Mar-2009 14:31:27   

Adapter v2.6

I currently fetch a collection of jobs like this:

       jobs = new EntityCollection<JobEntity>(new JobEntityFactory()); 

    var bucket = GetJobsBucket(filter);

    var tempContext = new Context();
    tempContext.Add(jobs);
    var sorter = new SortExpression(JobFields.Id | SortOperator.Descending);

    adapter.FetchEntityCollection(jobs, bucket, maxCount, sorter, JobListPrefetchPath(false));

    filter.TotalMatchesCount = adapter.GetDbCount(new JobEntityFactory().CreateFields(), bucket, null, false);
    filter.ReturnedMatchesCount = jobs.Count;

    tempContext.Clear();
    
    return jobs;

where bucket contains lots of predicates e.g.

        bucket.Relations.Add(JobEntity.Relations.JobTypeEntityUsingJobTypeFk);
        bucket.Relations.Add(JobTypeEntity.Relations.JobTypeCategoryEntityUsingCategoryFk);   
        var fieldCompareValuePredicate = new FieldCompareValuePredicate(JobTypeCategoryFields.Filter, null,
                        ComparisonOperator.Equal, filter.JobCategory) { CaseSensitiveCollation = true };                        
        bucket.PredicateExpression.Add(fieldCompareValuePredicate);

The Job entity has a collection of Attachments (via foreign key)

How can I filter the job list to only select jobs with one or more attachment? I know I could use a in-memory filter (AggregateSetPredicate) via a dynamic view but this will mean I will have to fetch all the jobs in order to get the correct counts, the current fetch has a maximum on the returned count.

Walaa avatar
Walaa
Support Team
Posts: 14993
Joined: 21-Aug-2005
# Posted on: 11-Mar-2009 15:31:24   

The Job entity has a collection of Attachments (via foreign key) How can I filter the job list to only select jobs with one or more attachment?

Either JOIN (add a relation) to the attachement table, this will surely return those entities with attachements

Or filter as follows:

SELECT * FROM Job 
WHERE Id IN (SELECT JobId FROM Attachements)

Which can be easily implemented using a FieldCompareSetPredicate

Posts: 48
Joined: 26-Mar-2007
# Posted on: 11-Mar-2009 15:56:24   

Thanks! Simple when you know how simple_smile

this is my working code for reference:

                    bucket.Relations.Add(JobEntity.Relations.AttachmentEntityUsingJobFk);
                    var filteredAttachments = new FieldCompareSetPredicate(JobFields.Id, null,
                                                                           AttachmentFields.JobFk, null,
                                                                           SetOperator.In, null);
                    bucket.PredicateExpression.Add(filteredAttachments);