Arad
Arad

Reputation: 12764

Which way of implemeting conditions in Entity Framework yields better performance?

When I want to do some validation stuff on database entities, I can think of two ways:

1: Retrive the field value and then do the calculations in the application:

if (dbContext.Coupons.Where(c=> c.Id == couponId).Select(c=> c.ExpirationDate).Single() <= DateTime.Now)

2: Do the calculations in the query (in 'Select()' method) and then retrive the result:

if (dbContext.Coupons.Where(c=> c.Id == couponId).Select(c=> c.ExpirationDate <= DateTime.Now).Single())

Upvotes: 0

Views: 65

Answers (2)

AGH
AGH

Reputation: 353

This will give you best performance.

if (dbContext.Coupons.Any(c => c.Id == couponId && c.ExpirationDate <= DateTime.Now))

Upvotes: 0

Lemons
Lemons

Reputation: 107

I suggest, every validation, filter or process do within linq or process that take value from db (SQL Query) or object.

for example :

if you have 10 datas in table and you use the second way, the app will import all data into local memory and filtered inside app.

but if you use the first way, the app only import the datas that already filtered (example only 4 datas after filter process)

if your datas is more than 10K maybe you'll see the different

Upvotes: 1

Related Questions