EF Core Notes (Cheat Sheet)

Md Asif AlamMd Asif Alam
3 min read

Here's a structured post for your EF Core Notes (Interactive/Cheat Sheet) with code snippets and details:


1. Required NuGet Packages

Data Access Layer (DAL):

API/MVC Project:

2. Configuring the DbContext

protected override void OnConfiguring(DbContextOptionsBuilder options)
{
    options.UseSqlServer("Server=(LocalDb)\\MSSQLLocalDB;Database=CodingWiki;TrustServerCertificate=True;Trusted_Connection=True;");
}

3. Renaming a Column

  • Change property name in entity.

  • Migrations:

    • Add-Migration RenameColumn

    • Update-Database

4. Seeding Data Through Migration

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // Precision
    modelBuilder.Entity<Book>()
        .Property(b => b.Price)
        .HasPrecision(10, 5);

    // Seed data
    modelBuilder.Entity<Book>().HasData(
        new Book { BookId = 1, Title = "Spider without Duty", ISBN = "123B12", Price = 10.99m }
        // ... more
    );
}

5. Typical Workflow

  • Code changes (add/update/seed, etc.)

  • Run:

    • Add-Migration <Name>

    • Update-Database

6. Example Entity

public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public string ISBN { get; set; }
    public decimal Price { get; set; }
}

7. Register Table

public DbSet<Book> Books { get; set; }

Entity Relationships & Data Annotations

1. Common Data Annotations

AnnotationPurposeExample
[Key]Primary key[Key] public int Id { get; set; }
[Required]Not null[Required] public string Name { get; set; }
[MaxLength]Max length[MaxLength(20)] public string ISBN { get; set; }
[NotMapped]Exclude from DB[NotMapped] public string Temp { get; set; }
[ForeignKey]Explicit FK[ForeignKey("Book")] public int BookId;

2. Entity Relationship Examples

One-to-One

public class Book
{
    public int BookId { get; set; }
    public BookDetail BookDetail { get; set; }
}

public class BookDetail
{
    [Key]
    public int BookDetail_Id { get; set; }
    [ForeignKey("Book")]
    public int Book_Id { get; set; }
    public Book Book { get; set; }
}

One-to-Many

public class Publisher
{
    [Key]
    public int Publisher_Id { get; set; }
    public List<Book> Books { get; set; }
}

public class Book
{
    [ForeignKey("Publisher")]
    public int Publisher_Id { get; set; }
    public Publisher Publisher { get; set; }
}

Many-to-Many (with mapping entity)

public class Author { ... public List<BookAuthorMap> BookAuthorMap { get; set; } }
public class Book   { ... public List<BookAuthorMap> BookAuthorMap { get; set; } }

public class BookAuthorMap
{
    [ForeignKey("Book")] public int Book_Id { get; set; }
    [ForeignKey("Author")] public int Author_Id { get; set; }
    public Book Book { get; set; }
    public Author Author { get; set; }
}

// Join with composite key
modelBuilder.Entity<BookAuthorMap>().HasKey(u => new { u.Author_Id, u.Book_Id });

3. Quick Attribute Summary

  • [Key] – Primary key

  • [Required] – Not null

  • [MaxLength(n)] – String length

  • [NotMapped] – Excluded from DB

  • [ForeignKey("Name")] – Explicit FK

4. Connection String Example

options.UseSqlServer("Server=(LocalDb)\\MSSQLLocalDB;Database=CodingWiki;TrustServerCertificate=True;Trusted_Connection=True;");

Additional Considerations

  • [Table("TableName")] annotation for changing table names.

  • [Column("ColName")] for explicit column mapping.

  • Indexes: [Index(nameof(PropertyName), IsUnique = true)] (from EF Core 5.0+).

  • Fluent configuration: modelBuilder.Entity<Book>().ToTable("Tbl_Books");

  • Cascade delete behavior: OnDelete(DeleteBehavior.Cascade)

Sample Additions

Change Table/Column Name

[Table("Tbl_Books")]
public class Book
{
    [Column("Book_ID")]
    public int BookId { get; set; }
    // ...
}

// Or in OnModelCreating:
modelBuilder.Entity<Book>().ToTable("Tbl_Books");
modelBuilder.Entity<Book>().Property(b => b.Title).HasColumnName("Book_Title");

Index Example

[Index(nameof(ISBN), IsUnique = true)]
public class Book { ... }

Cascade Delete Example

modelBuilder.Entity<Book>()
    .HasOne(b => b.Publisher)
    .WithMany(p => p.Books)
    .HasForeignKey(b => b.Publisher_Id)
    .OnDelete(DeleteBehavior.Restrict);

This cheat sheet provides a comprehensive guide to using EF Core effectively, with examples and annotations to help streamline your development process.

0
Subscribe to my newsletter

Read articles from Md Asif Alam directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Md Asif Alam
Md Asif Alam

🚀 Full Stack .NET Developer & React Enthusiast 👨‍💻 About Me: With 3+ years of experience, I'm passionate about crafting robust solutions and seamless user experiences through code. 💼 Expertise: Proficient in .NET Core API, ASP.NET MVC, React.js, and SQL. Skilled in backend architecture, RESTful APIs, and frontend development. 🌟 Achievements: Led projects enhancing scalability by 50%, delivered ahead of schedule, and contributed to open-source initiatives. 🔍 Future Focus: Eager to embrace new technologies and drive innovation in software development. 📫 Let's Connect: Open to new opportunities and collaborations. Reach me on LinkedIn or GitHub!