EF Core CRUD and Querying with LINQ
Create
csharp
using var db = new LibraryContext();
var author = new Author { Name = "Mark Twain" };
author.Books.Add(new Book { Title = "Tom Sawyer", Price = 12.5m, Year = 1876 });
author.Books.Add(new Book { Title = "Huckleberry Finn", Price = 14m, Year = 1884 });
db.Authors.Add(author); // adds the author and its books
int saved = await db.SaveChangesAsync(); // sends the INSERTs: returns 3
SaveChanges does the work:
Add, Remove and property changes are only remembered by EF. Nothing is written until you call SaveChangesAsync(). All changes are saved together in one transaction.
Read
csharp
Book? byKey = await db.Books.FindAsync(1); // by primary key, uses the cache first
var cheap = await db.Books
.Where(b => b.Price < 13m)
.OrderBy(b => b.Title)
.ToListAsync();
Book? tom = await db.Books.FirstOrDefaultAsync(b => b.Title == "Tom Sawyer");
bool any = await db.Books.AnyAsync(b => b.Year < 1800);
int count = await db.Books.CountAsync();
Update
csharp
var book = await db.Books.FirstAsync(b => b.Title == "Tom Sawyer");
book.Price = 15m; // EF notices the change (change tracking)
await db.SaveChangesAsync(); // UPDATE Books SET Price = 15 WHERE Id = ...
Delete
csharp
var old = await db.Books.FindAsync(2);
if (old is not null)
{
db.Books.Remove(old);
await db.SaveChangesAsync();
}
Update and Delete Many Rows Directly
csharp
await db.Books
.Where(b => b.Year < 1900)
.ExecuteUpdateAsync(s => s.SetProperty(b => b.Price, b => b.Price * 1.1m));
await db.Books
.Where(b => b.Price == 0)
.ExecuteDeleteAsync();
These run one SQL statement without loading rows into memory. They apply immediately and do not need SaveChanges.
Fast Read-Only Queries
csharp
var list = await db.Books.AsNoTracking().ToListAsync();
AsNoTracking() skips change tracking, which makes read-only queries faster and lighter.
Select Only What You Need
csharp
var summaries = await db.Books
.Where(b => b.Year > 1800)
.Select(b => new { b.Title, b.Price }) // SQL selects only these two columns
.ToListAsync();
Paging
csharp
int page = 2, size = 10;
var pageItems = await db.Books
.OrderBy(b => b.Id) // always sort when paging
.Skip((page - 1) * size)
.Take(size)
.ToListAsync();
Searching Text
csharp
var found = await db.Books
.Where(b => EF.Functions.Like(b.Title, "%Sawyer%"))
.ToListAsync();
| Do | Do not |
|---|---|
Filter in the query with Where before ToListAsync() | Load everything and filter in memory |
Use AsNoTracking for read-only data | Track thousands of entities you never change |
Use Select for lists and screens | Load whole entities with all columns |
| Use the async methods | Block threads with .ToList() in web apps |
Conclusion
EF Core tracks your changes and writes them with SaveChangesAsync. Write LINQ, filter in the database, project only needed columns and use ExecuteUpdate for bulk changes.
Quick Summary: Add/Remove + SaveChanges. Where before ToList. AsNoTracking for reads.

