[go: up one dir, main page]

0% found this document useful (0 votes)
421 views3 pages

Entity Framework Core Cheat Sheet

This document provides a cheat sheet on using Entity Framework Core, covering topics like creating and using a DbContext, performing CRUD operations, executing raw SQL, configuration conventions, and relationship mappings using Fluent API. Key information includes how to add, update, delete and find entities, load related data eagerly or explicitly, disable change tracking and queries, map entities to tables and columns, configure primary keys and indexes, and define one-to-one, one-to-many, and many-to-many relationships between entity types.

Uploaded by

jayanth romale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
421 views3 pages

Entity Framework Core Cheat Sheet

This document provides a cheat sheet on using Entity Framework Core, covering topics like creating and using a DbContext, performing CRUD operations, executing raw SQL, configuration conventions, and relationship mappings using Fluent API. Key information includes how to add, update, delete and find entities, load related data eagerly or explicitly, disable change tracking and queries, map entities to tables and columns, configure primary keys and indexes, and define one-to-one, one-to-many, and many-to-many relationships between entity types.

Uploaded by

jayanth romale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Entity Framework Core Cheat Sheet 1 Viastudy.

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

You might also like