Search code examples
entity-frameworkrazorlambdacheckboxfor

Set Razor CheckBoxFor checked value based on boolean property in a LinQ lambda


I can't seem to build this one up and i would like some suggestions. I have following Entities Product, Price and Discount.

Product has many prices and a Price has 1 product. 1 Price has many Discounts and 1 Discount has 1 Price.

I would like to define the 'Checked' status based on a boolean property 'IsActive' for a @CheckBoxFor(...) but i am struggling with this Lambda ...

The 'IsActive' property is not mapped, it's true or false based on the comparaison of the current date and start-end date of a Discount Entity.

@Html.CheckBoxFor(p => p.Product.Prices.Where(price => price.Product.ID == p.Product.ID && price.PriceType == BusinessLayer.Enums.PriceType.PurchasePrice && price.Discounts.Where(discount => discount.IsActive).SingleOrDefault().IsActive)

I also tried with a Select:

@Html.CheckBoxFor(p => p.Product.Prices.Where(price => price.Product.ID == p.Product.ID && price.PriceType == BusinessLayer.Enums.PriceType.PurchasePrice && price.Discounts.Select(d => d.IsActive)).IsActive)

Is my logic flawed, what am i doing wrong? Thank you very much for any feedback! Kind regards


Solution

  • Alright so i figured it out, i was not seeing it clearly. I needed to Take the Price first by using the .SingleOrDefault() after the first statement, afterwards, on that selection continue on the .Discounts property:

    @Html.CheckBoxFor(p => p.Product.Prices.Where(price => price.Product.ID == p.Product.ID && price.PriceType == BusinessLayer.Enums.PriceType.PurchasePrice).SingleOrDefault().Discounts.Where(d => d.IsActive).SingleOrDefault().IsActive
    

    Silly me :) Kind regards!