Search code examples
c#linqentity-frameworkpropertiescomputed-field

Query by computed property in EF


How can I query the objects by a computed property: My Book entity:

Book{
    //DB field
    bookID int PK,
    bookName nvarchar,
    artID int FK Article(artID)
    int OriginalPrice;
    int Discount;
    //computed
    public int SellPrice{
        get{
            return (OriginalPrice - OriginalPrice*Discount/100 )/500*500;
        }
    }

}

I want to select all the book have SellPrice > 5000, but I can't use the SellPrice in LINQ query string or lambda. I have done some googling and this is seem like good. But can't put my expression to calculate the SellPrice in a working way


Solution

  • Try this, it may help you:

    var books = (from e in context.Books.AsEnumerable()
                where ((e.OriginalPrice.ToDecimal() - e.OriginalPrice * e.Discount.ToDeciaml() / 100).ToDecimal() / 500 * 500) > 5000
                select e).ToList();
    

    Extension Method ToDecimal is

    public static class Extensions
        {            
            public static decimal ToDecimal(this int value)
            {
                return Convert.ToDecimal(value);
            }
        }