Search code examples
linqlinq-to-entities

linq to entity,How does the where clause use ?: Expression


TAB_XXX and TAB_XXX_details are one-to-many relationships, I need to query the two tables, however, we need to be filtered TAB_XXX_details

The code is as follows:

var qu = from c in db.TAB_XXX.Where(n => n.DELETE_MARK == false)
        let dets = c.TAB_XXX_DETAILS.Where(n => condition.SaleType.HasValue ? n.SALE_TYPE == (decimal)condition.SaleType : 1 == 1)
        select new
        {
            c,
            dets
        };

Condition.SaleType is number?, if the condition.SaleType is a valid number, such as 1, 2, 3 ... I want to filter the child record based on these numbers; when the condition.SaleType is null, I want to query TAB_XXX and all its child records;

How do I modify the where clause?

Thank you for your answer!


Solution

  • Since 1 == 1 is always true, your condition boils down to this:

    let dets = c.TAB_XXX_DETAILS
        .Where(n => !condition.SaleType.HasValue || n.SALE_TYPE == condition.SaleType.Value)
    

    Essentially, you want to return all rows when condition.SaleType does not have value; otherwise, you make a comparison to condition.SaleType.Value.