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

More Related Content

PPTX
Build your own entity with Drupal
KEY
Backbone.js Simple Tutorial
PDF
Ms Ajax Dom Element Class
PDF
Your Entity, Your Code
PDF
Entities in drupal 7
PDF
Top Ten Reasons to Use EntityFieldQuery in Drupal
ODP
Entity Query API
PDF
Drupal Entities - Emerging Patterns of Usage
Build your own entity with Drupal
Backbone.js Simple Tutorial
Ms Ajax Dom Element Class
Your Entity, Your Code
Entities in drupal 7
Top Ten Reasons to Use EntityFieldQuery in Drupal
Entity Query API
Drupal Entities - Emerging Patterns of Usage

What's hot (19)

PPT
Backbone js
PPTX
Drupal 7 entities & TextbookMadness.com
KEY
Django Pro ORM
PDF
jQuery secrets
PDF
Drupal - dbtng 25th Anniversary Edition
PDF
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
PPTX
Coding for Scale and Sanity
PDF
Building mobile web apps with Mobello
PDF
Drupal 8: Forms
PPTX
Drupal II: The SQL
PDF
Entity api
PPTX
jQuery
KEY
Advanced Django ORM techniques
PDF
Your code sucks, let's fix it - DPC UnCon
PDF
Class-based views with Django
PDF
Drupal Field API. Practical usage
PPT
J query
PPTX
J query1
PPTX
Drupal 8 migrate!
Backbone js
Drupal 7 entities & TextbookMadness.com
Django Pro ORM
jQuery secrets
Drupal - dbtng 25th Anniversary Edition
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
Coding for Scale and Sanity
Building mobile web apps with Mobello
Drupal 8: Forms
Drupal II: The SQL
Entity api
jQuery
Advanced Django ORM techniques
Your code sucks, let's fix it - DPC UnCon
Class-based views with Django
Drupal Field API. Practical usage
J query
J query1
Drupal 8 migrate!
Ad

Similar to Viastudy ef core_cheat_sheet (20)

PPTX
Entity Framework: Nakov @ BFU Hackhaton 2015
PDF
Understanding backbonejs
PPTX
Writing HTML5 Web Apps using Backbone.js and GAE
PPT
Sqlapi0.1
PPTX
jQuery, CSS3 and ColdFusion
PDF
Intro to Core Data
PDF
Backbone.js — Introduction to client-side JavaScript MVC
PPTX
Database Programming Techniques
PPT
Backbone js
PPT
Backbone.js
PDF
M.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMS
PPTX
Spring framework part 2
PPTX
State of entity framework
PPT
Lec9Handout.ppt
PPTX
Database Access With JDBC
PPTX
05 entity framework
PDF
Rp 6 session 2 naresh bhatia
PDF
Rails vs Web2py
PDF
Overview of The Scala Based Lift Web Framework
PDF
Scala based Lift Framework
Entity Framework: Nakov @ BFU Hackhaton 2015
Understanding backbonejs
Writing HTML5 Web Apps using Backbone.js and GAE
Sqlapi0.1
jQuery, CSS3 and ColdFusion
Intro to Core Data
Backbone.js — Introduction to client-side JavaScript MVC
Database Programming Techniques
Backbone js
Backbone.js
M.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMS
Spring framework part 2
State of entity framework
Lec9Handout.ppt
Database Access With JDBC
05 entity framework
Rp 6 session 2 naresh bhatia
Rails vs Web2py
Overview of The Scala Based Lift Web Framework
Scala based Lift Framework
Ad

More from imdurgesh (20)

PDF
Azure quick-start-for-net-developers
PDF
Sales Negotiating-for-entrepreneurs
PDF
Automated testing-whitepaper
PDF
Visual studio-2019-succinctly
PPTX
C# and .net framework
PDF
30 days-of-react-ebook-fullstackio
PDF
Linq pad succinctly
PDF
ViA Bootstrap 4
PDF
The road-to-learn-react
PDF
Public speaking for_geeks_succinctly
PDF
Google maps api_succinctly
PDF
W3 css succinctly
PDF
Aspnet core-2-succinctly
PDF
Cryptography in net_succinctly
PDF
Azure functions-succinctly
PDF
Nodejs succinctly
PDF
Angular succinctly
PDF
Reactjs succinctly
PDF
C sharp code_contracts_succinctly
PDF
Asp.net tutorial
Azure quick-start-for-net-developers
Sales Negotiating-for-entrepreneurs
Automated testing-whitepaper
Visual studio-2019-succinctly
C# and .net framework
30 days-of-react-ebook-fullstackio
Linq pad succinctly
ViA Bootstrap 4
The road-to-learn-react
Public speaking for_geeks_succinctly
Google maps api_succinctly
W3 css succinctly
Aspnet core-2-succinctly
Cryptography in net_succinctly
Azure functions-succinctly
Nodejs succinctly
Angular succinctly
Reactjs succinctly
C sharp code_contracts_succinctly
Asp.net tutorial

Recently uploaded (20)

PPTX
Pharma ospi slides which help in ospi learning
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PPTX
Institutional Correction lecture only . . .
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
A systematic review of self-coping strategies used by university students to ...
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Cell Types and Its function , kingdom of life
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
Cell Structure & Organelles in detailed.
PDF
01-Introduction-to-Information-Management.pdf
Pharma ospi slides which help in ospi learning
2.FourierTransform-ShortQuestionswithAnswers.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
human mycosis Human fungal infections are called human mycosis..pptx
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Institutional Correction lecture only . . .
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
A systematic review of self-coping strategies used by university students to ...
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Supply Chain Operations Speaking Notes -ICLT Program
Final Presentation General Medicine 03-08-2024.pptx
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Microbial disease of the cardiovascular and lymphatic systems
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Cell Types and Its function , kingdom of life
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Cell Structure & Organelles in detailed.
01-Introduction-to-Information-Management.pdf

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