-2

I struggled constructing and finding easily the correct info for defining the LINQ expressing for the criterion on the many-to-many, hence the Q&A.

Please modify/improve/correct/...

Basic situation:

  • .Net Entity Framework code first
  • We work with UnitOfWork repo's, but that's not really important here
  • We define a IQueryable<MyCustomMadeEntity> query
  • User submits his search criteria through a form, each criterion matching either directly a property of MyCustomMadeEntity, or a property of an another entity that has a many-to-many-relationship with MyCustomMadeEntity, e.g.:
public class MyCustomMadeEntity : BaseEntity
{
    public string ArticleCode { get; set; }
    public string Comment { get; set; }
    public Guid? ColorId { get; set; }
    public ArticleColor Color { get; set; }

    public ICollection<ArticleStatus> ArticleStatuses { get; set; }
}

with

public class MyCustomMadeEntity : BaseEntity
{
    // properties
    Public LocationType LocationType { get; set; }
}

(In the case LocationType is a custom made enum

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
qqtf
  • 632
  • 6
  • 17

1 Answers1

0
  1. Construct a base IQueryable<Entity> expressing the db source and the linkage of the base-table with other tables (join’s etc)
IQueryable<CustomMadeEntity> query = _UnitOfWork. ustomMadeEntityRepository
                    .Queryable()
                    .Include(el => el.OtherEntity);
query = PerformAdvancedSearch(criteria, query);

2.Modify the query variable step by step checking of the individual search criteria

public static IQueryable<CustomMadeEntity> PerformAdvancedSearch(SearchRequestDto criteria, IQueryable< CustomMadeEntity > query) 
{
    if (!string.IsNullOrWhiteSpace(criteria.ArticleCode))
    {
        query = query.Where(el => el. ArticleCode == criteria. ArticleCode));
    }
}

Additional query logic with contains, ><, …

if (something) 
{
    query = query.Where(el => el.ArticleStatuses.OrderByDescending(el => el.CreatedOn).Any() &&
                              el.ArticleStatuses.OrderByDescending(el => el.CreatedOn)
                 .FirstOrDefault().LocationType == criteria.LocationType);                  
} 
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
qqtf
  • 632
  • 6
  • 17