SlideShare una empresa de Scribd logo
Entity
Framework
Optimization
By Rajeev Harbola
Design Consideration
 Avoid to put all the DB Objects into One Single Entity Model.
 Disable change tracking for entity if not needed.
NorthwindDataContext context = new NorthwindDataContext()
context.tblCities.MergeOption = MergeOption.NoTracking;
 Avoid fetching all the fields if not required
//Bad Practice
var customer = (from cust in dataContext.Customers select cust).ToList();
//Good Practice
var customer = (from cust in dataContext.Customers
select new {
customer. CustomerID,customer.Name,customer.Address}ToList ();
 Use Compiled Query wherever needed
Design Consideration
• Avoid using Contains
• Retrieve only required number of records.
Coding Guidelines
• Do Not Count After Query Execution
var empCount = db.Employees .Where(x => x.CreateDate <
DateTime.Now.AddDays(-10) .Count() //only executes a SQL COUNT
var emps = db.Employees .Where(x => x.CreateDate <
DateTime.Now.AddDays(-10)
var empCount = emps.Count() // returns all matching employees and
then executes a count
• Filter Before ToList()
//ToList() executed too early
var emps = db.Employees .Where(x => x.CreateDate <
DateTime.Now.AddDays(-10) .ToList() // All employees created within last 10 days queried
.Take(50) // List is filtered for the top 50
//ToList() executed last
var emps = db.Employees .Where(x => x.CreateDate <
DateTime.Now.AddDays(-10) .Take(50) .ToList() //Query made for top
50 employees created within last 10 days
Coding Guidelines
• Don’t Load Entities To Delete Them (very important)
var emp = db.Employees.Find(empID); //Executes a query against the database
db.Employees.Remove(emp);
db.SaveChanges(); //Executes a second hit to the database
var emp = new Employee { ID = empID }
db.Employees.Attach(emp);
db.Employees.Remove(emp);
db.SaveChanges(); //Executes a single hit to the database
• Use Eager Loading Instead of Lazy Loading
var employees = db.Employees; foreach(var emp in employees)
{
var address = emp.Address; //Database query is executed every time this line is hit
}
var employees = db.Employees .Include(x => x.Address) .ToList(); //All data loaded from
database
foreach(var emp in employees)
{
var address = emp.Address; //No database query executed
}
Coding Guidelines
• Query In-Memory Entities First
var emp = db.Employees.Find(empID); //Executes a query against the database
db.Employees.Remove(emp);
db.SaveChanges(); //Executes a second hit to the database
var emp = new Employee { ID = empID }
db.Employees.Attach(emp);
db.Employees.Remove(emp);
db.SaveChanges(); //Executes a single hit to the database
• Use Eager Loading Instead of Lazy Loading
var emp = db.Employees.Find(empID); // Queries in memory first
var emp = db.Employees.Where(x => x.ID == empID); //Always hits the database
var emp = db.Employees.Local.Where(x => x.ID == empID) ;
Advanced
• Use Compiled Query wherever needed
// create the entity object
NorthwindEntities mobjentity = new NorthwindEntities();
//Simple Query
IQueryable lstCus = from customer in mobjentity.tblCustomers where customer.City == "Delhi"
select customer;
//Compiled Query
Func> compiledQuery= CompiledQuery.Compile>((ctx, city) =>from customer in ctx.Customers
where customer.City == city
select customer);
• Debug and Optimize LINQ Query
IQueryable lstCus = from customer in mobjentity.tblCustomers
where customer.City == "Delhi"
select customer;
lstCus.Dump();
Last but not least
• Don’t Rely on Entity Framework Exclusively For Data
Access
• Finally, EF is great for productivity but executing raw SQL
or a stored procedure may often produce performance
benefits.
• In EF 4.0 and above the DbContext the SQLQuery()
method to execute raw SQL:
• var emps = db.Database.SQLQuery("select email from
Employees");Similarly use ExecuteSqlCommand() to
execute a stored procedure:
• var emps = db.Database.ExecuteSqlCommand("...");
THANKS
&
No question please

Más contenido relacionado

La actualidad más candente

Ransack ruby on rails - HuanND
Ransack ruby on rails - HuanNDRansack ruby on rails - HuanND
Ransack ruby on rails - HuanND
Framgia Vietnam
 
Qtp training session IV
Qtp training session IVQtp training session IV
Qtp training session IV
Aisha Mazhar
 
Cubes – ways of deployment
Cubes – ways of deploymentCubes – ways of deployment
Cubes – ways of deployment
Stefan Urbanek
 

La actualidad más candente (18)

Angular JS deep dive
Angular JS deep diveAngular JS deep dive
Angular JS deep dive
 
Tech Talk - JPA and Query Optimization - publish
Tech Talk  -  JPA and Query Optimization - publishTech Talk  -  JPA and Query Optimization - publish
Tech Talk - JPA and Query Optimization - publish
 
Database c# connetion
Database c# connetionDatabase c# connetion
Database c# connetion
 
Ruby on Rails Developer - Allerin
Ruby on Rails Developer - AllerinRuby on Rails Developer - Allerin
Ruby on Rails Developer - Allerin
 
Core Data Migration
Core Data MigrationCore Data Migration
Core Data Migration
 
Dev411
Dev411Dev411
Dev411
 
Ransack ruby on rails - HuanND
Ransack ruby on rails - HuanNDRansack ruby on rails - HuanND
Ransack ruby on rails - HuanND
 
Deadlock Prevention in Operating System
Deadlock Prevention in Operating SystemDeadlock Prevention in Operating System
Deadlock Prevention in Operating System
 
Experiment no 05
Experiment no 05Experiment no 05
Experiment no 05
 
Influxdb and time series data
Influxdb and time series dataInfluxdb and time series data
Influxdb and time series data
 
MongoDB San Francisco DrupalCon 2010
MongoDB San Francisco DrupalCon 2010MongoDB San Francisco DrupalCon 2010
MongoDB San Francisco DrupalCon 2010
 
Code craftsmanship saturdays second session
Code craftsmanship saturdays second sessionCode craftsmanship saturdays second session
Code craftsmanship saturdays second session
 
Przywitaj się z reactive extensions
Przywitaj się z reactive extensionsPrzywitaj się z reactive extensions
Przywitaj się z reactive extensions
 
Qtp training session IV
Qtp training session IVQtp training session IV
Qtp training session IV
 
Cubes – ways of deployment
Cubes – ways of deploymentCubes – ways of deployment
Cubes – ways of deployment
 
Spring batch showCase
Spring batch showCaseSpring batch showCase
Spring batch showCase
 
Introduce spark (by 조창원)
Introduce spark (by 조창원)Introduce spark (by 조창원)
Introduce spark (by 조창원)
 
Spring batch in action
Spring batch in actionSpring batch in action
Spring batch in action
 

Destacado

Hispanoamerica- Estados Unidos quiere reconquistar su "patio trasero"- Sobera...
Hispanoamerica- Estados Unidos quiere reconquistar su "patio trasero"- Sobera...Hispanoamerica- Estados Unidos quiere reconquistar su "patio trasero"- Sobera...
Hispanoamerica- Estados Unidos quiere reconquistar su "patio trasero"- Sobera...
Ramón Copa
 
Situação de Aprendizagem - LP - texto "Pausa"
Situação de Aprendizagem - LP - texto "Pausa"Situação de Aprendizagem - LP - texto "Pausa"
Situação de Aprendizagem - LP - texto "Pausa"
Lidiane Santos
 

Destacado (14)

live here 2015 US Open (tennis)
live here 2015 US Open (tennis)live here 2015 US Open (tennis)
live here 2015 US Open (tennis)
 
Salesforce couse in chennai
Salesforce couse in chennaiSalesforce couse in chennai
Salesforce couse in chennai
 
Propuestas de gestión del trabajo social
Propuestas de gestión del trabajo socialPropuestas de gestión del trabajo social
Propuestas de gestión del trabajo social
 
China Youthology's Whitepaper with Kiehl's: China Youth Attitude and Practice...
China Youthology's Whitepaper with Kiehl's: China Youth Attitude and Practice...China Youthology's Whitepaper with Kiehl's: China Youth Attitude and Practice...
China Youthology's Whitepaper with Kiehl's: China Youth Attitude and Practice...
 
2015/07/29 Eric Pan talk at Meiji Univ -Grow the difference -
2015/07/29 Eric Pan talk at Meiji Univ -Grow the difference -2015/07/29 Eric Pan talk at Meiji Univ -Grow the difference -
2015/07/29 Eric Pan talk at Meiji Univ -Grow the difference -
 
Hispanoamerica- Estados Unidos quiere reconquistar su "patio trasero"- Sobera...
Hispanoamerica- Estados Unidos quiere reconquistar su "patio trasero"- Sobera...Hispanoamerica- Estados Unidos quiere reconquistar su "patio trasero"- Sobera...
Hispanoamerica- Estados Unidos quiere reconquistar su "patio trasero"- Sobera...
 
Desafuero parlamentario y acción penal privada
Desafuero parlamentario y acción penal privadaDesafuero parlamentario y acción penal privada
Desafuero parlamentario y acción penal privada
 
Energia electrica
Energia electricaEnergia electrica
Energia electrica
 
Situação de Aprendizagem - LP - texto "Pausa"
Situação de Aprendizagem - LP - texto "Pausa"Situação de Aprendizagem - LP - texto "Pausa"
Situação de Aprendizagem - LP - texto "Pausa"
 
live 2015 US Open (tennis) on mac
live 2015 US Open (tennis) on maclive 2015 US Open (tennis) on mac
live 2015 US Open (tennis) on mac
 
Blue Ocean Academy Training Infographic
Blue Ocean Academy Training InfographicBlue Ocean Academy Training Infographic
Blue Ocean Academy Training Infographic
 
certificate[1]
certificate[1]certificate[1]
certificate[1]
 
Broadcast 2015 US Open (tennis) live
Broadcast 2015 US Open (tennis) liveBroadcast 2015 US Open (tennis) live
Broadcast 2015 US Open (tennis) live
 
FPSB India- Resource Person Certificate
FPSB India- Resource Person CertificateFPSB India- Resource Person Certificate
FPSB India- Resource Person Certificate
 

Similar a Entity framework

Parallel programming patterns - Олександр Павлишак
Parallel programming patterns - Олександр ПавлишакParallel programming patterns - Олександр Павлишак
Parallel programming patterns - Олександр Павлишак
Igor Bronovskyy
 
Salesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUGSalesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUG
vraopolisetti
 
Dm adapter RubyConf.TW
Dm adapter RubyConf.TWDm adapter RubyConf.TW
Dm adapter RubyConf.TW
codingforrent
 

Similar a Entity framework (20)

Indexed db
Indexed dbIndexed db
Indexed db
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
Parallel programming patterns - Олександр Павлишак
Parallel programming patterns - Олександр ПавлишакParallel programming patterns - Олександр Павлишак
Parallel programming patterns - Олександр Павлишак
 
Parallel programming patterns (UA)
Parallel programming patterns (UA)Parallel programming patterns (UA)
Parallel programming patterns (UA)
 
Slickdemo
SlickdemoSlickdemo
Slickdemo
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
 
JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
 
Salesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUGSalesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUG
 
My SQL Skills Killed the Server
My SQL Skills Killed the ServerMy SQL Skills Killed the Server
My SQL Skills Killed the Server
 
Sql killedserver
Sql killedserverSql killedserver
Sql killedserver
 
High Performance Core Data
High Performance Core DataHigh Performance Core Data
High Performance Core Data
 
Do something in 5 with gas 2-graduate to a database
Do something in 5 with gas 2-graduate to a databaseDo something in 5 with gas 2-graduate to a database
Do something in 5 with gas 2-graduate to a database
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
 
Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1
 
Dm adapter RubyConf.TW
Dm adapter RubyConf.TWDm adapter RubyConf.TW
Dm adapter RubyConf.TW
 
IndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceIndexedDB - Querying and Performance
IndexedDB - Querying and Performance
 
Linq
LinqLinq
Linq
 
Core Data Migrations and A Better Option
Core Data Migrations and A Better OptionCore Data Migrations and A Better Option
Core Data Migrations and A Better Option
 

Último

Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
mbmh111980
 

Último (20)

De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
GraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisGraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysis
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdf
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in Michelangelo
 
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024
 
A Guideline to Gorgias to to Re:amaze Data Migration
A Guideline to Gorgias to to Re:amaze Data MigrationA Guideline to Gorgias to to Re:amaze Data Migration
A Guideline to Gorgias to to Re:amaze Data Migration
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
Benefits of Employee Monitoring Software
Benefits of  Employee Monitoring SoftwareBenefits of  Employee Monitoring Software
Benefits of Employee Monitoring Software
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Crafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationCrafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM Integration
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning Framework
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
KLARNA - Language Models and Knowledge Graphs: A Systems Approach
KLARNA -  Language Models and Knowledge Graphs: A Systems ApproachKLARNA -  Language Models and Knowledge Graphs: A Systems Approach
KLARNA - Language Models and Knowledge Graphs: A Systems Approach
 
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
 

Entity framework

  • 2. Design Consideration  Avoid to put all the DB Objects into One Single Entity Model.  Disable change tracking for entity if not needed. NorthwindDataContext context = new NorthwindDataContext() context.tblCities.MergeOption = MergeOption.NoTracking;  Avoid fetching all the fields if not required //Bad Practice var customer = (from cust in dataContext.Customers select cust).ToList(); //Good Practice var customer = (from cust in dataContext.Customers select new { customer. CustomerID,customer.Name,customer.Address}ToList ();  Use Compiled Query wherever needed
  • 3. Design Consideration • Avoid using Contains • Retrieve only required number of records.
  • 4. Coding Guidelines • Do Not Count After Query Execution var empCount = db.Employees .Where(x => x.CreateDate < DateTime.Now.AddDays(-10) .Count() //only executes a SQL COUNT var emps = db.Employees .Where(x => x.CreateDate < DateTime.Now.AddDays(-10) var empCount = emps.Count() // returns all matching employees and then executes a count • Filter Before ToList() //ToList() executed too early var emps = db.Employees .Where(x => x.CreateDate < DateTime.Now.AddDays(-10) .ToList() // All employees created within last 10 days queried .Take(50) // List is filtered for the top 50 //ToList() executed last var emps = db.Employees .Where(x => x.CreateDate < DateTime.Now.AddDays(-10) .Take(50) .ToList() //Query made for top 50 employees created within last 10 days
  • 5. Coding Guidelines • Don’t Load Entities To Delete Them (very important) var emp = db.Employees.Find(empID); //Executes a query against the database db.Employees.Remove(emp); db.SaveChanges(); //Executes a second hit to the database var emp = new Employee { ID = empID } db.Employees.Attach(emp); db.Employees.Remove(emp); db.SaveChanges(); //Executes a single hit to the database • Use Eager Loading Instead of Lazy Loading var employees = db.Employees; foreach(var emp in employees) { var address = emp.Address; //Database query is executed every time this line is hit } var employees = db.Employees .Include(x => x.Address) .ToList(); //All data loaded from database foreach(var emp in employees) { var address = emp.Address; //No database query executed }
  • 6. Coding Guidelines • Query In-Memory Entities First var emp = db.Employees.Find(empID); //Executes a query against the database db.Employees.Remove(emp); db.SaveChanges(); //Executes a second hit to the database var emp = new Employee { ID = empID } db.Employees.Attach(emp); db.Employees.Remove(emp); db.SaveChanges(); //Executes a single hit to the database • Use Eager Loading Instead of Lazy Loading var emp = db.Employees.Find(empID); // Queries in memory first var emp = db.Employees.Where(x => x.ID == empID); //Always hits the database var emp = db.Employees.Local.Where(x => x.ID == empID) ;
  • 7. Advanced • Use Compiled Query wherever needed // create the entity object NorthwindEntities mobjentity = new NorthwindEntities(); //Simple Query IQueryable lstCus = from customer in mobjentity.tblCustomers where customer.City == "Delhi" select customer; //Compiled Query Func> compiledQuery= CompiledQuery.Compile>((ctx, city) =>from customer in ctx.Customers where customer.City == city select customer); • Debug and Optimize LINQ Query IQueryable lstCus = from customer in mobjentity.tblCustomers where customer.City == "Delhi" select customer; lstCus.Dump();
  • 8. Last but not least • Don’t Rely on Entity Framework Exclusively For Data Access • Finally, EF is great for productivity but executing raw SQL or a stored procedure may often produce performance benefits. • In EF 4.0 and above the DbContext the SQLQuery() method to execute raw SQL: • var emps = db.Database.SQLQuery("select email from Employees");Similarly use ExecuteSqlCommand() to execute a stored procedure: • var emps = db.Database.ExecuteSqlCommand("...");