c# - Optimizing LINQ Query using Entity Framework -


i have following linq query product information using entity framework

productdetails.items = (from productdetail in db.tolist()                             select new prod                             {                                 id = productdetail.id                             prodname = productdetail.productname,                                         ...                                         ...                                         ...                                         ...                             calaculation1 = getcalaculation(productdetail.calc1),                             calaculation1 = getcalaculation(productdetail.calc2),                                         ...                                         ...                                         ...                                         ...                                         calaculation15 = getcalaculation(productdetail.calc3)                             }                         ).tolist(); 

where getcalaculation method queries db using linq. query slow if fetching 100's of records. how can optimize it?

first of structure of select looks "little" problematic me since fetching 15 calaculation properties each record. if create view in data base have 15 joins calculations table bad performance. first thing should review object structure , confirm need calculations fetched in 1 request. if insist structure can not changed here steps improve performance:

  1. if tables don't change may consider create materialized view (view clustered index in sql server) contain calculated data. in case query fast inserts/updates in tables slower.
  2. do not use db.tolist() in query - doing fetch table in memory , issue separate queries each 1 of calculations.

  3. i little confused query:

    var dbquery = calculation in db.calculations                calculation.calc == calc1 select calculation);  var totalsum = (from xyz in dbquery select (decimal?)xyz.calc).sum() ?? 0; 

you fetching records have calc == calc1 , calculating sum? wouldn't easier count how many records have calc == calc1 , multiply calc1

db.calculations.count(c=>c.calc == calc1) * calc1; 
  1. it cheaper fetch calculations table memory product table ( var calctable = db.calculations.tolist() ) if has limited number of records getcalaculation work in-memory objects faster. if going may consider in parallel or in separate tasks.

Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -