SlideShare ist ein Scribd-Unternehmen logo
1 von 3
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comJD Leonard
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Editionddiers
 
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legione-Legion
 
Coding for Scale and Sanity
Coding for Scale and SanityCoding for Scale and Sanity
Coding for Scale and SanityJimKellerES
 
Building mobile web apps with Mobello
Building mobile web apps with MobelloBuilding mobile web apps with Mobello
Building mobile web apps with MobelloJeong-Geun Kim
 
Drupal 8: Forms
Drupal 8: FormsDrupal 8: Forms
Drupal 8: Formsdrubb
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQLddiers
 
Advanced Django ORM techniques
Advanced Django ORM techniquesAdvanced Django ORM techniques
Advanced Django ORM techniquesDaniel 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 UnConRafael Dohms
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with DjangoSimon Willison
 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usagePavel Makhrinsky
 

Was ist angesagt? (19)

Backbone js
Backbone jsBackbone js
Backbone js
 
Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.com
 
Django Pro ORM
Django Pro ORMDjango Pro ORM
Django Pro ORM
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
 
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
 
Coding for Scale and Sanity
Coding for Scale and SanityCoding for Scale and Sanity
Coding for Scale and Sanity
 
Building mobile web apps with Mobello
Building mobile web apps with MobelloBuilding mobile web apps with Mobello
Building mobile web apps with Mobello
 
Drupal 8: Forms
Drupal 8: FormsDrupal 8: Forms
Drupal 8: Forms
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQL
 
Entity api
Entity apiEntity api
Entity api
 
jQuery
jQueryjQuery
jQuery
 
Advanced Django ORM techniques
Advanced Django ORM techniquesAdvanced Django ORM techniques
Advanced Django ORM techniques
 
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
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with Django
 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usage
 
J query
J queryJ query
J query
 
J query1
J query1J query1
J query1
 
Drupal 8 migrate!
Drupal 8 migrate!Drupal 8 migrate!
Drupal 8 migrate!
 

Ähnlich wie Viastudy ef core_cheat_sheet

Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Svetlin Nakov
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick 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 GAERon Reiter
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core DataMake 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 MVCpootsbook
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming TechniquesRaji 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 PROGRAMSSupriya Radhakrishna
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2Haroon Idrees
 
State of entity framework
State of entity frameworkState of entity framework
State of entity frameworkDavid Paquette
 
05 entity framework
05 entity framework05 entity framework
05 entity frameworkglubox
 
Rp 6 session 2 naresh bhatia
Rp 6  session 2 naresh bhatiaRp 6  session 2 naresh bhatia
Rp 6 session 2 naresh bhatiasapientindia
 
Rails vs Web2py
Rails vs Web2pyRails vs Web2py
Rails vs Web2pyjonromero
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkIndicThreads
 

Ähnlich wie 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
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
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
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 
jQuery, CSS3 and ColdFusion
jQuery, CSS3 and ColdFusionjQuery, CSS3 and ColdFusion
jQuery, CSS3 and ColdFusion
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
 
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
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
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
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
 
State of entity framework
State of entity frameworkState of entity framework
State of entity framework
 
Lec9Handout.ppt
Lec9Handout.pptLec9Handout.ppt
Lec9Handout.ppt
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
05 entity framework
05 entity framework05 entity framework
05 entity framework
 
Rp 6 session 2 naresh bhatia
Rp 6  session 2 naresh bhatiaRp 6  session 2 naresh bhatia
Rp 6 session 2 naresh bhatia
 
Rails vs Web2py
Rails vs Web2pyRails vs Web2py
Rails vs Web2py
 
Overview Of Lift Framework
Overview Of Lift FrameworkOverview Of Lift Framework
Overview Of Lift Framework
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web Framework
 

Mehr von imdurgesh

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

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

Kürzlich hochgeladen

ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 

Kürzlich hochgeladen (20)

ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 

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