SlideShare a Scribd company logo
Entity Framework Core Cheat Sheet 1 Viastudy.com
Platforms
.NET Framework (Console, Winform, WPF, ASP.NET)
.NET Core (Console, ASP.NET Core)
Mono & Xamarin (in-progress)
UWP (in-progress)
EF Core - Working with DbContext
Create and use DbContext object
using (var context = new SchoolContext())
{
//work with context here
}
Create Operation
context.Add<Student>(newStudentObj);
context.SaveChanges()
//or
context.Students.Add(newStudentObj);
context.SaveChanges();
// or
context.Entry(newStudentObj).State = EntityState.Added;
context.SaveChanges();
Update Operation
context.Update<Student>(StudentObj);
context.SaveChanges();
//or
context.Entry(studentObj).State = EntityState.Modified;
context.SaveChanges();
Delete Operation
Context.Remove(studentObj);
context.SaveChanges();
//or
context.Entry(studentObj).State = EntityState.Deleted;
context.SaveChanges();
Get the current State of an entity
varstate = context.Entry<Student>(studentObj).State;
Execute raw SQL query for entity types
varsList = context.Students.FromSql($"Select * from
Student where StudentName=’name’").ToList<Student>();
Execute raw SQL commands
int noOfRowsAffected =
context.Database.ExecuteSqlCommand("CUD command");
Explicitly load navigation /reference entity
context.Entry(student).Reference(s => s.Grade).Load();
Explicitly Load Collection
context.Entry(student).Collection(s=>s.Courses).Load();
Find by PrimaryKey
var student = context.Students.Find(1); Disable
automatic detect changes
context.ChangeTracker.AutoDetectChangesEnabled = false
Disable Query Tracking
context.ChangeTracker.QueryTrackingBehavior =
QueryTrackingBehavior.NoTracking;
Disable Automatic Detect Changes
context.ChangeTracker.AutoDetectChangesEnabled = false;
Eager Loading
context.Students.Where(s => s.FirstName == "Bill")
.Include(s => s.Grade).FirstOrDefault();
Multi Level Eager Loading
context.Students.Where(s => s.FirstName == "Bill")
.Include(s => s.Grade)
.ThenInclude(g => g.Teachers);
EF Core Conventions
Schema
dbo
Table Name
Same as DbSet<TEntity> property name in the context class.
Primary key Name
1) Id
2) <Entity Class Name> Id (case insensitive)
e.g. Id or StudentId property becomes primary key of Student by
default.
Foreign key property Name
EF Core API will create a foreign key column for each reference
navigation property in an entity with one of the following naming
patterns.
1. <Reference Navigation Property Name>Id
2. <Reference Navigation Property Name><Principal Primary Key
Property Name>
Null column
All reference type properties and nullable primitive properties.
NotNull Column
PrimaryKey properties and non-nullable primitive properties (int,
decimal, datetime, float etc.)
Index
Clustered index on PrimaryKey columns.
Non-clustered index on Foreignkey columns.
Properties mapping to DB
By default all properties will map to database.
Cascade delete
Enabled by default.
EF Core Fluent API - Entity Type Configurations
ToTable() - Maps an entity to database table
modelBuilder.Entity<Student>().ToTable("StudentInfo");
modelBuilder.Entity<Student>()
.ToTable("StudentInfo", "dbo");
ToTable() – Maps two entities to one database table
modelBuilder.Entity<Student>().ToTable("Student");
modelBuilder.Entity<StudentDeail>()
.ToTable("Student");
HasKey() - Configures Primary Key(s)
modelBuilder.Entity<Student>().HasKey(s => s.StudId);
HasAlternateKey() - Configures an alternate key in the EF
model
modelBuilder.Entity<Student>().HasAlternateKey(s=>s.Id)
Entity Framework Core Cheat Sheet 2 Viastudy.com
HasIndex() - Configures an index on the specified
properties
modelBuilder.Entity<Student>().HasIndex(s => s.Id)
HasOne() - Configures the One part of the relationship
modelBuilder.Entity<Student>().HasOne(s => s.Grade)
HasMany() - Configures the Many part of the relationship
modelBuilder.Entity<Student>().HasMany(s => s.Courses)
OwnsOne() - Configures a relationship where the target
entity is owned by this entity
modelBuilder.Entity<Student>()
.OwnsOne(p => p.HomeAddress)
.OwnsOne(p => p.PermanentAddress);
EF Core Fluent API – Property Configuration
HasColumnType - Configures a column data type
modelBuilder.Entity<Student>()
.Property(s => s.StudentName)
.HasColumnType("varchar");
HasColumnName - Configures a Column name
modelBuilder.Entity<Student>()
.Property(s => s.StudentName)
.HasColumnName("Name");
HasDefaultValue - Configures a default value
modelBuilder.Entity<Student>()
.Property(s => s.PendingFees)
.HasDefaultValue(100);
HasComputedColumnSql - Configures a computed
column
modelBuilder.Entity<Student>()
.Property(s => s.PendingFees)
.HasComputedColumnSql(“Sql here”);
IsRequired - Configures a Null column
modelBuilder.Entity<Student>().Property(s =>
s.DoB).IsRequired(false);
IsRequired - Configures a NotNull column
modelBuilder.Entity<Student>()
.Property(s => s.DoB)
.IsRequired();
HasMaxLength - Configures maximum Length for
string column
modelBuilder.Entity<Student>()
.Property(s => s.StudentName)
.HasMaxLength(50);
IsUnicode - Configures a Unicode string column
modelBuilder.Entity<Student>()
.Property(s => s.StudentName)
.IsUnicode();
//or
modelBuilder.Entity<Student>()
.Property(s => s.StudentName)
.IsUnicode(false);
IsConcurrencyToken – Configures a concurrency
property
modelBuilder.Entity<Student>()
.Property(p => p.StudentName)
.IsConcurrencyToken();
//or
modelBuilder.Entity<Student>()
.Property(p => p.RowVersion)
.IsRowVersion();
HasField - Configures a backing field
modelBuilder.Entity<Student>()
.Property(s => s.StudentName)
.HasField("_StudentName");
EF Core Fluent API – Relationship Configurations
One-to-zero-or-one
modelBuilder.Entity<Student>()
.HasOne<StudentAddress>(s =>
s.Address)
.WithOne(ad => ad.Student)
One-to-Many
modelBuilder.Entity<Student>()
.HasOne<Grade>(s => s.Grade)
.WithMany(g => g.Students)
Many-to-Many
modelBuilder.Entity<StudentCourse>()
.HasKey(sc => new {
sc.StudentId,
sc.CourseId
});
modelBuilder.Entity<StudentCourse>()
.HasOne<Student>(sc => sc.Student)
.WithMany(s => s.StudentCourses);
modelBuilder.Entity<StudentCourse>()
.HasOne<Course>(sc => sc.Course)
.WithMany(s => s.StudentCourses);
Entity Framework Core Cheat Sheet 3 Viastudy.com
Features EF Core
DB-First - Command line 1.0
DB-First -VS Wizard X
Identity Key Generation 1.0
Global query filter 2.0
DB Scalar function 2.0
Model-First X
Code-First 1.0
Mixed client/server
evaluation
1.0
DbContext & DbSet 1.0
LINQ-to-Entities 1.0
ChangeTracker 1.0
Automated Migration X
Code-based Migration 1.0
Eager Loading 1.0
Proxy Entity X
Interception X
Simple Logging X
GroupBy Transaction 2.1
Graphical Visualization X
of EDM
Raw SQL Queries: Entity
Types
1.0
EDM Wizard X Raw SQL Queries: non- 2.1
Querying using
EntitySQL
X
entity types
DbContext Pooling 2.0
Table per hierarchy 1.0
Table per type X
Data annotations 1.0
Fluent API 1.0
Table per concrete class X Model Format: EDMX X
Many-to-Many without X
join entity
(XML)
Entity Splitting X
Spatial Data X
Lazy loading 2.1
Stored procedure
mapping with entity for X
CUD operation
Seed Data 2.1
Complex Type/Owned X
types
Table splitting 2.0
Field Mapping 1.1
Shadow properties 1.0
Alternate Keys 1.0
Ad

More Related Content

What's hot (19)

Backbone js
Backbone jsBackbone js
Backbone js
husnara mohammad
 
Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.com
JD Leonard
 
Django Pro ORM
Django Pro ORMDjango Pro ORM
Django Pro ORM
Alex Gaynor
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
Bastian Feder
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
ddiers
 
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
e-Legion
 
Coding for Scale and Sanity
Coding for Scale and SanityCoding for Scale and Sanity
Coding for Scale and Sanity
JimKellerES
 
Building mobile web apps with Mobello
Building mobile web apps with MobelloBuilding mobile web apps with Mobello
Building mobile web apps with Mobello
Jeong-Geun Kim
 
Drupal 8: Forms
Drupal 8: FormsDrupal 8: Forms
Drupal 8: Forms
drubb
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQL
ddiers
 
Entity api
Entity apiEntity api
Entity api
Bishant Shrestha
 
jQuery
jQueryjQuery
jQuery
Jay Poojara
 
Advanced Django ORM techniques
Advanced Django ORM techniquesAdvanced Django ORM techniques
Advanced Django ORM techniques
Daniel Roseman
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
Rafael Dohms
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with Django
Simon Willison
 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usage
Pavel Makhrinsky
 
J query
J queryJ query
J query
Manav Prasad
 
J query1
J query1J query1
J query1
Manav Prasad
 
Drupal 8 migrate!
Drupal 8 migrate!Drupal 8 migrate!
Drupal 8 migrate!
Pavel Makhrinsky
 
Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.com
JD Leonard
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
ddiers
 
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
e-Legion
 
Coding for Scale and Sanity
Coding for Scale and SanityCoding for Scale and Sanity
Coding for Scale and Sanity
JimKellerES
 
Building mobile web apps with Mobello
Building mobile web apps with MobelloBuilding mobile web apps with Mobello
Building mobile web apps with Mobello
Jeong-Geun Kim
 
Drupal 8: Forms
Drupal 8: FormsDrupal 8: Forms
Drupal 8: Forms
drubb
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQL
ddiers
 
Advanced Django ORM techniques
Advanced Django ORM techniquesAdvanced Django ORM techniques
Advanced Django ORM techniques
Daniel Roseman
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
Rafael Dohms
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with Django
Simon Willison
 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usage
Pavel Makhrinsky
 

Similar to Viastudy ef core_cheat_sheet (20)

Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015
Svetlin Nakov
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
Nick Lee
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
Ron Reiter
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
jitendral
 
jQuery, CSS3 and ColdFusion
jQuery, CSS3 and ColdFusionjQuery, CSS3 and ColdFusion
jQuery, CSS3 and ColdFusion
Denard Springle IV
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
Make School
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
pootsbook
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
Raji Ghawi
 
Backbone js
Backbone jsBackbone js
Backbone js
Knoldus Inc.
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
Knoldus Inc.
 
M.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMS
M.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMSM.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMS
M.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMS
Supriya Radhakrishna
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
Haroon Idrees
 
State of entity framework
State of entity frameworkState of entity framework
State of entity framework
David Paquette
 
Lec9Handout.ppt
Lec9Handout.pptLec9Handout.ppt
Lec9Handout.ppt
MOMEKEMKUEFOUETDUREL
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
Dharani Kumar Madduri
 
05 entity framework
05 entity framework05 entity framework
05 entity framework
glubox
 
Rp 6 session 2 naresh bhatia
Rp 6  session 2 naresh bhatiaRp 6  session 2 naresh bhatia
Rp 6 session 2 naresh bhatia
sapientindia
 
Rails vs Web2py
Rails vs Web2pyRails vs Web2py
Rails vs Web2py
jonromero
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Framework
vhazrati
 
Overview Of Lift Framework
Overview Of Lift FrameworkOverview Of Lift Framework
Overview Of Lift Framework
Xebia IT Architects
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015
Svetlin Nakov
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
Nick Lee
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
Ron Reiter
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
Make School
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
pootsbook
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
Raji Ghawi
 
M.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMS
M.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMSM.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMS
M.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMS
Supriya Radhakrishna
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
Haroon Idrees
 
State of entity framework
State of entity frameworkState of entity framework
State of entity framework
David Paquette
 
05 entity framework
05 entity framework05 entity framework
05 entity framework
glubox
 
Rp 6 session 2 naresh bhatia
Rp 6  session 2 naresh bhatiaRp 6  session 2 naresh bhatia
Rp 6 session 2 naresh bhatia
sapientindia
 
Rails vs Web2py
Rails vs Web2pyRails vs Web2py
Rails vs Web2py
jonromero
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Framework
vhazrati
 
Ad

More from imdurgesh (20)

Azure quick-start-for-net-developers
Azure quick-start-for-net-developersAzure quick-start-for-net-developers
Azure quick-start-for-net-developers
imdurgesh
 
Sales Negotiating-for-entrepreneurs
Sales Negotiating-for-entrepreneursSales Negotiating-for-entrepreneurs
Sales Negotiating-for-entrepreneurs
imdurgesh
 
Automated testing-whitepaper
Automated testing-whitepaperAutomated testing-whitepaper
Automated testing-whitepaper
imdurgesh
 
Visual studio-2019-succinctly
Visual studio-2019-succinctlyVisual studio-2019-succinctly
Visual studio-2019-succinctly
imdurgesh
 
C# and .net framework
C# and .net frameworkC# and .net framework
C# and .net framework
imdurgesh
 
30 days-of-react-ebook-fullstackio
30 days-of-react-ebook-fullstackio30 days-of-react-ebook-fullstackio
30 days-of-react-ebook-fullstackio
imdurgesh
 
Linq pad succinctly
Linq pad succinctlyLinq pad succinctly
Linq pad succinctly
imdurgesh
 
ViA Bootstrap 4
ViA Bootstrap 4ViA Bootstrap 4
ViA Bootstrap 4
imdurgesh
 
The road-to-learn-react
The road-to-learn-reactThe road-to-learn-react
The road-to-learn-react
imdurgesh
 
Public speaking for_geeks_succinctly
Public speaking for_geeks_succinctlyPublic speaking for_geeks_succinctly
Public speaking for_geeks_succinctly
imdurgesh
 
Google maps api_succinctly
Google maps api_succinctlyGoogle maps api_succinctly
Google maps api_succinctly
imdurgesh
 
W3 css succinctly
W3 css succinctlyW3 css succinctly
W3 css succinctly
imdurgesh
 
Aspnet core-2-succinctly
Aspnet core-2-succinctlyAspnet core-2-succinctly
Aspnet core-2-succinctly
imdurgesh
 
Cryptography in net_succinctly
Cryptography in net_succinctlyCryptography in net_succinctly
Cryptography in net_succinctly
imdurgesh
 
Azure functions-succinctly
Azure functions-succinctlyAzure functions-succinctly
Azure functions-succinctly
imdurgesh
 
Nodejs succinctly
Nodejs succinctlyNodejs succinctly
Nodejs succinctly
imdurgesh
 
Angular succinctly
Angular succinctlyAngular succinctly
Angular succinctly
imdurgesh
 
Reactjs succinctly
Reactjs succinctlyReactjs succinctly
Reactjs succinctly
imdurgesh
 
C sharp code_contracts_succinctly
C sharp code_contracts_succinctlyC sharp code_contracts_succinctly
C sharp code_contracts_succinctly
imdurgesh
 
Asp.net tutorial
Asp.net tutorialAsp.net tutorial
Asp.net tutorial
imdurgesh
 
Azure quick-start-for-net-developers
Azure quick-start-for-net-developersAzure quick-start-for-net-developers
Azure quick-start-for-net-developers
imdurgesh
 
Sales Negotiating-for-entrepreneurs
Sales Negotiating-for-entrepreneursSales Negotiating-for-entrepreneurs
Sales Negotiating-for-entrepreneurs
imdurgesh
 
Automated testing-whitepaper
Automated testing-whitepaperAutomated testing-whitepaper
Automated testing-whitepaper
imdurgesh
 
Visual studio-2019-succinctly
Visual studio-2019-succinctlyVisual studio-2019-succinctly
Visual studio-2019-succinctly
imdurgesh
 
C# and .net framework
C# and .net frameworkC# and .net framework
C# and .net framework
imdurgesh
 
30 days-of-react-ebook-fullstackio
30 days-of-react-ebook-fullstackio30 days-of-react-ebook-fullstackio
30 days-of-react-ebook-fullstackio
imdurgesh
 
Linq pad succinctly
Linq pad succinctlyLinq pad succinctly
Linq pad succinctly
imdurgesh
 
ViA Bootstrap 4
ViA Bootstrap 4ViA Bootstrap 4
ViA Bootstrap 4
imdurgesh
 
The road-to-learn-react
The road-to-learn-reactThe road-to-learn-react
The road-to-learn-react
imdurgesh
 
Public speaking for_geeks_succinctly
Public speaking for_geeks_succinctlyPublic speaking for_geeks_succinctly
Public speaking for_geeks_succinctly
imdurgesh
 
Google maps api_succinctly
Google maps api_succinctlyGoogle maps api_succinctly
Google maps api_succinctly
imdurgesh
 
W3 css succinctly
W3 css succinctlyW3 css succinctly
W3 css succinctly
imdurgesh
 
Aspnet core-2-succinctly
Aspnet core-2-succinctlyAspnet core-2-succinctly
Aspnet core-2-succinctly
imdurgesh
 
Cryptography in net_succinctly
Cryptography in net_succinctlyCryptography in net_succinctly
Cryptography in net_succinctly
imdurgesh
 
Azure functions-succinctly
Azure functions-succinctlyAzure functions-succinctly
Azure functions-succinctly
imdurgesh
 
Nodejs succinctly
Nodejs succinctlyNodejs succinctly
Nodejs succinctly
imdurgesh
 
Angular succinctly
Angular succinctlyAngular succinctly
Angular succinctly
imdurgesh
 
Reactjs succinctly
Reactjs succinctlyReactjs succinctly
Reactjs succinctly
imdurgesh
 
C sharp code_contracts_succinctly
C sharp code_contracts_succinctlyC sharp code_contracts_succinctly
C sharp code_contracts_succinctly
imdurgesh
 
Asp.net tutorial
Asp.net tutorialAsp.net tutorial
Asp.net tutorial
imdurgesh
 
Ad

Recently uploaded (20)

UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 

Viastudy ef core_cheat_sheet

  • 1. Entity Framework Core Cheat Sheet 1 Viastudy.com Platforms .NET Framework (Console, Winform, WPF, ASP.NET) .NET Core (Console, ASP.NET Core) Mono & Xamarin (in-progress) UWP (in-progress) EF Core - Working with DbContext Create and use DbContext object using (var context = new SchoolContext()) { //work with context here } Create Operation context.Add<Student>(newStudentObj); context.SaveChanges() //or context.Students.Add(newStudentObj); context.SaveChanges(); // or context.Entry(newStudentObj).State = EntityState.Added; context.SaveChanges(); Update Operation context.Update<Student>(StudentObj); context.SaveChanges(); //or context.Entry(studentObj).State = EntityState.Modified; context.SaveChanges(); Delete Operation Context.Remove(studentObj); context.SaveChanges(); //or context.Entry(studentObj).State = EntityState.Deleted; context.SaveChanges(); Get the current State of an entity varstate = context.Entry<Student>(studentObj).State; Execute raw SQL query for entity types varsList = context.Students.FromSql($"Select * from Student where StudentName=’name’").ToList<Student>(); Execute raw SQL commands int noOfRowsAffected = context.Database.ExecuteSqlCommand("CUD command"); Explicitly load navigation /reference entity context.Entry(student).Reference(s => s.Grade).Load(); Explicitly Load Collection context.Entry(student).Collection(s=>s.Courses).Load(); Find by PrimaryKey var student = context.Students.Find(1); Disable automatic detect changes context.ChangeTracker.AutoDetectChangesEnabled = false Disable Query Tracking context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; Disable Automatic Detect Changes context.ChangeTracker.AutoDetectChangesEnabled = false; Eager Loading context.Students.Where(s => s.FirstName == "Bill") .Include(s => s.Grade).FirstOrDefault(); Multi Level Eager Loading context.Students.Where(s => s.FirstName == "Bill") .Include(s => s.Grade) .ThenInclude(g => g.Teachers); EF Core Conventions Schema dbo Table Name Same as DbSet<TEntity> property name in the context class. Primary key Name 1) Id 2) <Entity Class Name> Id (case insensitive) e.g. Id or StudentId property becomes primary key of Student by default. Foreign key property Name EF Core API will create a foreign key column for each reference navigation property in an entity with one of the following naming patterns. 1. <Reference Navigation Property Name>Id 2. <Reference Navigation Property Name><Principal Primary Key Property Name> Null column All reference type properties and nullable primitive properties. NotNull Column PrimaryKey properties and non-nullable primitive properties (int, decimal, datetime, float etc.) Index Clustered index on PrimaryKey columns. Non-clustered index on Foreignkey columns. Properties mapping to DB By default all properties will map to database. Cascade delete Enabled by default. EF Core Fluent API - Entity Type Configurations ToTable() - Maps an entity to database table modelBuilder.Entity<Student>().ToTable("StudentInfo"); modelBuilder.Entity<Student>() .ToTable("StudentInfo", "dbo"); ToTable() – Maps two entities to one database table modelBuilder.Entity<Student>().ToTable("Student"); modelBuilder.Entity<StudentDeail>() .ToTable("Student"); HasKey() - Configures Primary Key(s) modelBuilder.Entity<Student>().HasKey(s => s.StudId); HasAlternateKey() - Configures an alternate key in the EF model modelBuilder.Entity<Student>().HasAlternateKey(s=>s.Id)
  • 2. Entity Framework Core Cheat Sheet 2 Viastudy.com HasIndex() - Configures an index on the specified properties modelBuilder.Entity<Student>().HasIndex(s => s.Id) HasOne() - Configures the One part of the relationship modelBuilder.Entity<Student>().HasOne(s => s.Grade) HasMany() - Configures the Many part of the relationship modelBuilder.Entity<Student>().HasMany(s => s.Courses) OwnsOne() - Configures a relationship where the target entity is owned by this entity modelBuilder.Entity<Student>() .OwnsOne(p => p.HomeAddress) .OwnsOne(p => p.PermanentAddress); EF Core Fluent API – Property Configuration HasColumnType - Configures a column data type modelBuilder.Entity<Student>() .Property(s => s.StudentName) .HasColumnType("varchar"); HasColumnName - Configures a Column name modelBuilder.Entity<Student>() .Property(s => s.StudentName) .HasColumnName("Name"); HasDefaultValue - Configures a default value modelBuilder.Entity<Student>() .Property(s => s.PendingFees) .HasDefaultValue(100); HasComputedColumnSql - Configures a computed column modelBuilder.Entity<Student>() .Property(s => s.PendingFees) .HasComputedColumnSql(“Sql here”); IsRequired - Configures a Null column modelBuilder.Entity<Student>().Property(s => s.DoB).IsRequired(false); IsRequired - Configures a NotNull column modelBuilder.Entity<Student>() .Property(s => s.DoB) .IsRequired(); HasMaxLength - Configures maximum Length for string column modelBuilder.Entity<Student>() .Property(s => s.StudentName) .HasMaxLength(50); IsUnicode - Configures a Unicode string column modelBuilder.Entity<Student>() .Property(s => s.StudentName) .IsUnicode(); //or modelBuilder.Entity<Student>() .Property(s => s.StudentName) .IsUnicode(false); IsConcurrencyToken – Configures a concurrency property modelBuilder.Entity<Student>() .Property(p => p.StudentName) .IsConcurrencyToken(); //or modelBuilder.Entity<Student>() .Property(p => p.RowVersion) .IsRowVersion(); HasField - Configures a backing field modelBuilder.Entity<Student>() .Property(s => s.StudentName) .HasField("_StudentName"); EF Core Fluent API – Relationship Configurations One-to-zero-or-one modelBuilder.Entity<Student>() .HasOne<StudentAddress>(s => s.Address) .WithOne(ad => ad.Student) One-to-Many modelBuilder.Entity<Student>() .HasOne<Grade>(s => s.Grade) .WithMany(g => g.Students) Many-to-Many modelBuilder.Entity<StudentCourse>() .HasKey(sc => new { sc.StudentId, sc.CourseId }); modelBuilder.Entity<StudentCourse>() .HasOne<Student>(sc => sc.Student) .WithMany(s => s.StudentCourses); modelBuilder.Entity<StudentCourse>() .HasOne<Course>(sc => sc.Course) .WithMany(s => s.StudentCourses);
  • 3. Entity Framework Core Cheat Sheet 3 Viastudy.com Features EF Core DB-First - Command line 1.0 DB-First -VS Wizard X Identity Key Generation 1.0 Global query filter 2.0 DB Scalar function 2.0 Model-First X Code-First 1.0 Mixed client/server evaluation 1.0 DbContext & DbSet 1.0 LINQ-to-Entities 1.0 ChangeTracker 1.0 Automated Migration X Code-based Migration 1.0 Eager Loading 1.0 Proxy Entity X Interception X Simple Logging X GroupBy Transaction 2.1 Graphical Visualization X of EDM Raw SQL Queries: Entity Types 1.0 EDM Wizard X Raw SQL Queries: non- 2.1 Querying using EntitySQL X entity types DbContext Pooling 2.0 Table per hierarchy 1.0 Table per type X Data annotations 1.0 Fluent API 1.0 Table per concrete class X Model Format: EDMX X Many-to-Many without X join entity (XML) Entity Splitting X Spatial Data X Lazy loading 2.1 Stored procedure mapping with entity for X CUD operation Seed Data 2.1 Complex Type/Owned X types Table splitting 2.0 Field Mapping 1.1 Shadow properties 1.0 Alternate Keys 1.0