EF Core Database Helper Methods and Concepts

Md Asif AlamMd Asif Alam
2 min read

Here's a concise note summarizing the Entity Framework Core (EF Core) database helper methods and concepts from your code:

1. Database Initialization & Migration

using(ApplicationDbContext context = new())
{
    context.Database.EnsureCreated();
    if (context.Database.GetPendingMigrations().Count() > 0) 
    {
        context.Database.Migrate();
    }
}
  • Ensures database is created.

  • Applies pending migrations automatically.

2. Logging Configuration

protected override void OnConfiguring(DbContextOptionsBuilder options)
{
    options.UseSqlServer("connectionString")
           .LogTo(Console.WriteLine, new[] { DbLoggerCategory.Database.Command.Name }, LogLevel.Information);
}
  • Logs SQL commands executed by EF Core to the console with Information log level.

3. Get All Books

void GetAllBooks()
{
    using var context = new ApplicationDbContext();
    var books = context.Books.ToList();
    foreach (var book in books)
        Console.WriteLine(book.Title + " - " + book.ISBN);
}

4. Add a Book

void AddBook()
{
    Book book = new() { Title = "New EF Core Book", ISBN = "1231231212", Price = 10.93m, Publisher_Id = 1 };
    using var context = new ApplicationDbContext();
    context.Books.Add(book);
    context.SaveChanges();
}

5. Get One Book (First or Default)

void GetBook()
{
    using var context = new ApplicationDbContext();
    var book = context.Books.FirstOrDefault();
    Console.WriteLine(book?.Title + " - " + book?.ISBN);
}

6. Filtering with Where

var book = context.Books.Where(u => u.Publisher_Id == 3 && u.Price > 30).FirstOrDefault();

7. Find by Primary Key

var book = context.Books.Find(1002);

8. Single or Default

var book = context.Books.SingleOrDefault(u => u.Publisher_Id == 66);
  • Throws if multiple matches exist.

9. Contains, Like, Aggregation

var books = context.Books.Where(u => EF.Functions.Like(u.ISBN, "12%"));

10. Deferred Execution

var books = context.Books; // Query is not executed yet
foreach (var book in books)
    Console.WriteLine(book.Title + " - " + book.ISBN); // Query executes here

11. Pagination (Skip and Take)

var books = context.Books.Skip(4).Take(1);

12. Update Books

void UpdateBook()
{
    using var context = new ApplicationDbContext();
    var books = context.Books.Where(u => u.Publisher_Id == 1);
    foreach (var book in books)
        book.Price = 55.55m;
    context.SaveChanges();
}

13. Delete Book

void DeleteBook()
{
    using var context = new ApplicationDbContext();
    var book = context.Books.Find(1003);
    context.Books.Remove(book);
    context.SaveChanges();
}

This covers the main database helper methods and EF Core concepts demonstrated in your code snippet, including CRUD operations, filtering, pagination, and logging. Let me know if you want a more detailed explanation or examples!

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!