SlideShare a Scribd company logo
1 of 10
Entity Framework
Practices
LINKNODE, NOV 2014
Web Programming Principles
1. Do not get far more than what we need
2. Database connection/query is expensive (Try to work all in one go as much as we can)
3. D-R-Y (Don’t Repeat Yourself)
Issues
• Single function has been used for multiple purposes
• GetProjectByID (projectId)
• Project info
• Org info
• Related Licenses
• Project viewpoints, Terrain Services, Reference Structures, PDF files
• Project overlays
• Project layouts
• Turbines
• Turbine spec
• Turbine model
• Nearby org cumulative projects
• Nearby national cumulative projects
• National cumulative turbines
• Snapshots
• ….
public string GetProjectName(int projectId)
{
var project = GetProjectByID(projectId);
return project.Name;
}
public int GetNumberOfViewpoints(int projectId)
{
var project = GetProjectByID(projectId);
return project.Viewpoints.Count();
}
Violate principle #1
Issues – It’s even worse
* Entity Framework SQL Query Generation
* N+1 problem (common mistake)
public BusinessObjects.Project GetProjectByID(int projectId)
{
using (var db = ProjectsEntities1.Create())
{
BusinessObjects.Project projectObj = null;
var projectData = db.Projects.Where(n => n.UID == projectId).SingleOrDefault();
if (projectData != null)
{
projectObj = tblProject.CreateObject(projectData);
foreach (var viewPointData in projectData.ViewPoints)
{
var viewPointObj = tblViewPoint.CreateObject(viewPointData);
projectObj.ViewPoints.Add(viewPointObj);
}
}
return projectObj;
}
}
“Behind the scene”
1 query to retrieve project info
N queries to retrieve N viewpoints of project
 Total 1+N queries just to retrieve a simple data
 Given we have M projects, it would take M*(1+N)
amount of queries to get data from database!
Violate principle #2
Lazy loading
Best Practices
Best Practices (option 1.)
public class ProjectBasic
{
public ProjectBasic(ProjectBasic projectBasic) : this()
{
Utils.CopyProperties<ProjectBasic>(projectBasic, this);
}
public int UID { get; set; }
public int OrganizationUID { get; set; }
public string Name { get; set; }
public System.DateTime DateAdded { get; set; }
}
public class ProjectWithViewPoint : ProjectBasic
{
//Basic data
public ProjectWithViewPoint(ProjectBasic projectBasic)
: base(projectBasic) {}
//Additional data
public List<BusinessObjects.ViewPoint> ViewPoints { get; set; }
}
public static BusinessObjects.ProjectBasic GetProjectByID(int projectId, ProjectsEntities1 db)
{
BusinessObjects.ProjectBasic projectObjBasic = null;
var projectData = db.Projects.Where(n => n.UID == projectId).SingleOrDefault();
if (projectData != null)
projectObjBasic = tblProject.CreateObjectBasic(projectData);
return projectObjBasic;
}
public BusinessObjects.ProjectWithViewPoint GetProjectWithViewPoints(int projectId)
{
using (var db = ProjectsEntities1.Create())
{
BusinessObjects.ProjectWithViewPoint projectObj = null;
BusinessObjects.ProjectBasic projectBasicObj = GetProjectByID(projectId, db);
if (projectBasicObj != null)
{
//Create new from basic data (with auto-copied constructor)
projectObj = new BusinessObjects.ProjectWithViewPoint(projectBasicObj);
//Query additional data we need in one go under the same connection DB
var dataViewPoints = db.ViewPoints.Where(n => n.ProjectUID == projectId);
foreach (var dataViewPoint in dataViewPoints)
{
var viewPointObj = tblViewPoint.CreateObject(dataViewPoint);
projectObj.ViewPoints.Add(viewPointObj);
}
}
return projectObj;
}
}
Best Practices (option 2.) using System.Data.Entity;
public BusinessObjects.ProjectWithViewPoint GetProjectWithViewPoints(int projectId)
{
using (var db = ProjectsEntities1.Create())
{
db.Configuration.LazyLoadingEnabled = false;
BusinessObjects.ProjectWithViewPoint projectObj = null;
var projectData = db.Projects
.Include(n => n.ViewPoints)
.Where(n => n.UID == projectId).SingleOrDefault();
if (projectData != null)
{
var projectBasic = tblProject.CreateObjectBasic(projectData);
//Create new from basic data (with auto-copied constructor)
projectObj = new BusinessObjects.ProjectWithViewPoint(projectBasic);
//Query additional data with include enabled
foreach (var dataViewPoint in projectData.ViewPoints)
{
var viewPointObj = tblViewPoint.CreateObject(dataViewPoint);
projectObj.ViewPoints.Add(viewPointObj);
}
}
return projectObj;
}
}
public class ProjectBasic
{
public ProjectBasic(ProjectBasic projectBasic) : this()
{
Utils.CopyProperties<ProjectBasic>(projectBasic, this);
}
public int UID { get; set; }
public int OrganizationUID { get; set; }
public string Name { get; set; }
public System.DateTime DateAdded { get; set; }
}
public class ProjectWithViewPoint : ProjectBasic
{
//Basic data
public ProjectWithViewPoint(ProjectBasic projectBasic)
: base(projectBasic) {}
//Additional data
public List<BusinessObjects.ViewPoint> ViewPoints { get; set; }
}
Best Practices (cont.)
public static BusinessObjects.ProjectBasic CreateObjectBasic(Project projectData)
{
BusinessObjects.ProjectBasic retsult = new ProjectBasic();
result.UID = projectData.UID;
result.OrganisationUID = projectData.OrganisationUID;
result.Name = projectData.Name;
result.DateAdded = projectData.DateAdded;
return result;
}
public static void CopyProperties<T>(T fromObj, T toObj)
{
var propertiesInfo = typeof(T).GetProperties();
var toObjType = toObj.GetType();
foreach (var propertyInfo in propertiesInfo)
{
var valueToSet = propertyInfo.GetValue(fromObj, null);
toObjType.GetProperty(propertyInfo.Name).SetValue(toObj, valueToSet, null);
}
}
Best Practices (cont.)
* CreateObject function just simply to create BusinessObject from DataObject (That’s all! Do
NOT query or load related objects)
* Construct a full business object by:
◦ Based on basic data object
◦ Query related objects separately in one go as much as we can (within a same connection)
◦ Construct a full object by merging related objects
◦ Or Use “Include” keyword (System.Data.Entity) – Carefully to use this!
* Split data access function into DB-reuse and Non-DB-reuse.
Conclusions
1. Do not get far more than what we need
2. Database connection/query is expensive
 Query data at one time and arrange data in memory instead of working directly in database
3. D-R-Y (Don’t Repeat Yourself)
4. Following best practices!

More Related Content

Similar to Entity framework practices

My way to clean android (EN) - Android day salamanca edition
My way to clean android (EN) - Android day salamanca editionMy way to clean android (EN) - Android day salamanca edition
My way to clean android (EN) - Android day salamanca editionChristian Panadero
 
My way to clean android - Android day salamanca edition
My way to clean android - Android day salamanca editionMy way to clean android - Android day salamanca edition
My way to clean android - Android day salamanca editionChristian Panadero
 
A (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project FilesA (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project FilesDavid Wengier
 
Android data binding
Android data bindingAndroid data binding
Android data bindingAjit Singh
 
The Best Way to Become an Android Developer Expert with Android Jetpack
The Best Way to Become an Android Developer Expert  with Android JetpackThe Best Way to Become an Android Developer Expert  with Android Jetpack
The Best Way to Become an Android Developer Expert with Android JetpackAhmad Arif Faizin
 
CDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptorCDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptorCaelum
 
Android Design Patterns
Android Design PatternsAndroid Design Patterns
Android Design PatternsGodfrey Nolan
 
Of plugins and decorators - trivago's e2e test framework in the spotlight
Of plugins and decorators - trivago's e2e test framework in the spotlightOf plugins and decorators - trivago's e2e test framework in the spotlight
Of plugins and decorators - trivago's e2e test framework in the spotlightBenjamin Bischoff
 
第一次用Parse就深入淺出
第一次用Parse就深入淺出第一次用Parse就深入淺出
第一次用Parse就深入淺出Ymow Wu
 
Converting Your Mobile App to the Mobile Cloud
Converting Your Mobile App to the Mobile CloudConverting Your Mobile App to the Mobile Cloud
Converting Your Mobile App to the Mobile CloudRoger Brinkley
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel.NET Conf UY
 
Developing iOS REST Applications
Developing iOS REST ApplicationsDeveloping iOS REST Applications
Developing iOS REST Applicationslmrei
 
State of search | drupalcamp ghent
State of search | drupalcamp ghentState of search | drupalcamp ghent
State of search | drupalcamp ghentJoris Vercammen
 
안드로이드 데이터 바인딩
안드로이드 데이터 바인딩안드로이드 데이터 바인딩
안드로이드 데이터 바인딩GDG Korea
 
Lewis Chiu Portfolio
Lewis Chiu PortfolioLewis Chiu Portfolio
Lewis Chiu PortfolioLewisChiu
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know Norberto Leite
 
Mongo+java (1)
Mongo+java (1)Mongo+java (1)
Mongo+java (1)MongoDB
 

Similar to Entity framework practices (20)

My way to clean android (EN) - Android day salamanca edition
My way to clean android (EN) - Android day salamanca editionMy way to clean android (EN) - Android day salamanca edition
My way to clean android (EN) - Android day salamanca edition
 
Green dao
Green daoGreen dao
Green dao
 
My way to clean android - Android day salamanca edition
My way to clean android - Android day salamanca editionMy way to clean android - Android day salamanca edition
My way to clean android - Android day salamanca edition
 
A (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project FilesA (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project Files
 
Annotation processing tool
Annotation processing toolAnnotation processing tool
Annotation processing tool
 
Android data binding
Android data bindingAndroid data binding
Android data binding
 
The Best Way to Become an Android Developer Expert with Android Jetpack
The Best Way to Become an Android Developer Expert  with Android JetpackThe Best Way to Become an Android Developer Expert  with Android Jetpack
The Best Way to Become an Android Developer Expert with Android Jetpack
 
CDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptorCDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptor
 
Android Design Patterns
Android Design PatternsAndroid Design Patterns
Android Design Patterns
 
Of plugins and decorators - trivago's e2e test framework in the spotlight
Of plugins and decorators - trivago's e2e test framework in the spotlightOf plugins and decorators - trivago's e2e test framework in the spotlight
Of plugins and decorators - trivago's e2e test framework in the spotlight
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
第一次用Parse就深入淺出
第一次用Parse就深入淺出第一次用Parse就深入淺出
第一次用Parse就深入淺出
 
Converting Your Mobile App to the Mobile Cloud
Converting Your Mobile App to the Mobile CloudConverting Your Mobile App to the Mobile Cloud
Converting Your Mobile App to the Mobile Cloud
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel
 
Developing iOS REST Applications
Developing iOS REST ApplicationsDeveloping iOS REST Applications
Developing iOS REST Applications
 
State of search | drupalcamp ghent
State of search | drupalcamp ghentState of search | drupalcamp ghent
State of search | drupalcamp ghent
 
안드로이드 데이터 바인딩
안드로이드 데이터 바인딩안드로이드 데이터 바인딩
안드로이드 데이터 바인딩
 
Lewis Chiu Portfolio
Lewis Chiu PortfolioLewis Chiu Portfolio
Lewis Chiu Portfolio
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
 
Mongo+java (1)
Mongo+java (1)Mongo+java (1)
Mongo+java (1)
 

More from Minh Ng

3D Scanning & Reconstruction with Kinect
3D Scanning & Reconstruction with Kinect3D Scanning & Reconstruction with Kinect
3D Scanning & Reconstruction with KinectMinh Ng
 
WebGL - 3D programming
WebGL - 3D programmingWebGL - 3D programming
WebGL - 3D programmingMinh Ng
 
SignalR tutorial & best practices
SignalR tutorial & best practicesSignalR tutorial & best practices
SignalR tutorial & best practicesMinh Ng
 
Provider pattern practices
Provider pattern practicesProvider pattern practices
Provider pattern practicesMinh Ng
 
Open Data practices
Open Data practicesOpen Data practices
Open Data practicesMinh Ng
 
Monogame Content Pipeline practices
Monogame Content Pipeline practicesMonogame Content Pipeline practices
Monogame Content Pipeline practicesMinh Ng
 

More from Minh Ng (6)

3D Scanning & Reconstruction with Kinect
3D Scanning & Reconstruction with Kinect3D Scanning & Reconstruction with Kinect
3D Scanning & Reconstruction with Kinect
 
WebGL - 3D programming
WebGL - 3D programmingWebGL - 3D programming
WebGL - 3D programming
 
SignalR tutorial & best practices
SignalR tutorial & best practicesSignalR tutorial & best practices
SignalR tutorial & best practices
 
Provider pattern practices
Provider pattern practicesProvider pattern practices
Provider pattern practices
 
Open Data practices
Open Data practicesOpen Data practices
Open Data practices
 
Monogame Content Pipeline practices
Monogame Content Pipeline practicesMonogame Content Pipeline practices
Monogame Content Pipeline practices
 

Recently uploaded

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 

Recently uploaded (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

Entity framework practices

  • 2. Web Programming Principles 1. Do not get far more than what we need 2. Database connection/query is expensive (Try to work all in one go as much as we can) 3. D-R-Y (Don’t Repeat Yourself)
  • 3. Issues • Single function has been used for multiple purposes • GetProjectByID (projectId) • Project info • Org info • Related Licenses • Project viewpoints, Terrain Services, Reference Structures, PDF files • Project overlays • Project layouts • Turbines • Turbine spec • Turbine model • Nearby org cumulative projects • Nearby national cumulative projects • National cumulative turbines • Snapshots • …. public string GetProjectName(int projectId) { var project = GetProjectByID(projectId); return project.Name; } public int GetNumberOfViewpoints(int projectId) { var project = GetProjectByID(projectId); return project.Viewpoints.Count(); } Violate principle #1
  • 4. Issues – It’s even worse * Entity Framework SQL Query Generation * N+1 problem (common mistake) public BusinessObjects.Project GetProjectByID(int projectId) { using (var db = ProjectsEntities1.Create()) { BusinessObjects.Project projectObj = null; var projectData = db.Projects.Where(n => n.UID == projectId).SingleOrDefault(); if (projectData != null) { projectObj = tblProject.CreateObject(projectData); foreach (var viewPointData in projectData.ViewPoints) { var viewPointObj = tblViewPoint.CreateObject(viewPointData); projectObj.ViewPoints.Add(viewPointObj); } } return projectObj; } } “Behind the scene” 1 query to retrieve project info N queries to retrieve N viewpoints of project  Total 1+N queries just to retrieve a simple data  Given we have M projects, it would take M*(1+N) amount of queries to get data from database! Violate principle #2 Lazy loading
  • 6. Best Practices (option 1.) public class ProjectBasic { public ProjectBasic(ProjectBasic projectBasic) : this() { Utils.CopyProperties<ProjectBasic>(projectBasic, this); } public int UID { get; set; } public int OrganizationUID { get; set; } public string Name { get; set; } public System.DateTime DateAdded { get; set; } } public class ProjectWithViewPoint : ProjectBasic { //Basic data public ProjectWithViewPoint(ProjectBasic projectBasic) : base(projectBasic) {} //Additional data public List<BusinessObjects.ViewPoint> ViewPoints { get; set; } } public static BusinessObjects.ProjectBasic GetProjectByID(int projectId, ProjectsEntities1 db) { BusinessObjects.ProjectBasic projectObjBasic = null; var projectData = db.Projects.Where(n => n.UID == projectId).SingleOrDefault(); if (projectData != null) projectObjBasic = tblProject.CreateObjectBasic(projectData); return projectObjBasic; } public BusinessObjects.ProjectWithViewPoint GetProjectWithViewPoints(int projectId) { using (var db = ProjectsEntities1.Create()) { BusinessObjects.ProjectWithViewPoint projectObj = null; BusinessObjects.ProjectBasic projectBasicObj = GetProjectByID(projectId, db); if (projectBasicObj != null) { //Create new from basic data (with auto-copied constructor) projectObj = new BusinessObjects.ProjectWithViewPoint(projectBasicObj); //Query additional data we need in one go under the same connection DB var dataViewPoints = db.ViewPoints.Where(n => n.ProjectUID == projectId); foreach (var dataViewPoint in dataViewPoints) { var viewPointObj = tblViewPoint.CreateObject(dataViewPoint); projectObj.ViewPoints.Add(viewPointObj); } } return projectObj; } }
  • 7. Best Practices (option 2.) using System.Data.Entity; public BusinessObjects.ProjectWithViewPoint GetProjectWithViewPoints(int projectId) { using (var db = ProjectsEntities1.Create()) { db.Configuration.LazyLoadingEnabled = false; BusinessObjects.ProjectWithViewPoint projectObj = null; var projectData = db.Projects .Include(n => n.ViewPoints) .Where(n => n.UID == projectId).SingleOrDefault(); if (projectData != null) { var projectBasic = tblProject.CreateObjectBasic(projectData); //Create new from basic data (with auto-copied constructor) projectObj = new BusinessObjects.ProjectWithViewPoint(projectBasic); //Query additional data with include enabled foreach (var dataViewPoint in projectData.ViewPoints) { var viewPointObj = tblViewPoint.CreateObject(dataViewPoint); projectObj.ViewPoints.Add(viewPointObj); } } return projectObj; } } public class ProjectBasic { public ProjectBasic(ProjectBasic projectBasic) : this() { Utils.CopyProperties<ProjectBasic>(projectBasic, this); } public int UID { get; set; } public int OrganizationUID { get; set; } public string Name { get; set; } public System.DateTime DateAdded { get; set; } } public class ProjectWithViewPoint : ProjectBasic { //Basic data public ProjectWithViewPoint(ProjectBasic projectBasic) : base(projectBasic) {} //Additional data public List<BusinessObjects.ViewPoint> ViewPoints { get; set; } }
  • 8. Best Practices (cont.) public static BusinessObjects.ProjectBasic CreateObjectBasic(Project projectData) { BusinessObjects.ProjectBasic retsult = new ProjectBasic(); result.UID = projectData.UID; result.OrganisationUID = projectData.OrganisationUID; result.Name = projectData.Name; result.DateAdded = projectData.DateAdded; return result; } public static void CopyProperties<T>(T fromObj, T toObj) { var propertiesInfo = typeof(T).GetProperties(); var toObjType = toObj.GetType(); foreach (var propertyInfo in propertiesInfo) { var valueToSet = propertyInfo.GetValue(fromObj, null); toObjType.GetProperty(propertyInfo.Name).SetValue(toObj, valueToSet, null); } }
  • 9. Best Practices (cont.) * CreateObject function just simply to create BusinessObject from DataObject (That’s all! Do NOT query or load related objects) * Construct a full business object by: ◦ Based on basic data object ◦ Query related objects separately in one go as much as we can (within a same connection) ◦ Construct a full object by merging related objects ◦ Or Use “Include” keyword (System.Data.Entity) – Carefully to use this! * Split data access function into DB-reuse and Non-DB-reuse.
  • 10. Conclusions 1. Do not get far more than what we need 2. Database connection/query is expensive  Query data at one time and arrange data in memory instead of working directly in database 3. D-R-Y (Don’t Repeat Yourself) 4. Following best practices!