Andiana
Andiana

Reputation: 1952

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

Upvotes: 1

Views: 624

Answers (2)

M. Nasir Javaid
M. Nasir Javaid

Reputation: 5990

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);
        }
    }

Upvotes: 1

bubi
bubi

Reputation: 6501

You can't use computed expressions without materializing query.
In your case you can explode the expression inside a LINQ query. I think you are using /500*500 to truncate at 500 units.

var books = context.Books.Where(b => ((int)((OriginalPrice - (int)(OriginalPrice * Discount / 100) )/500))*500 > 5000).ToList();

Upvotes: 2

Related Questions