11 Jun 2025 #csharp #todayilearned
Every time we retrieve an entity with Entity Framework Core, it will track those entities in its change tracker. And when calling .SaveChanges()
, those changes are persisted to the database.
For read-only queries, we can add .AsNoTracking()
to make them faster.
But when projecting an entity into a custom object, there’s no need to add AsNoTracking()
since Entity Framework doesn’t track query results with a type different from the underlying entity type. Source
For example, let’s save some movies and retrieve them with and without a custom projection,
using Microsoft.EntityFrameworkCore;
namespace LookMaEntityFrameworkDoesNotTrackProjections;
public class Movie
{
public int Id { get; set; }
public string Name { get; set; }
public int ReleaseYear { get; set; }
}
public class MovieContext : DbContext
{
public MovieContext(DbContextOptions<MovieContext> options) : base(options)
{
}
public DbSet<Movie> Movies { get; set; }
}
[TestClass]
public class MovieTests
{
[TestMethod]
public void EFDoesNotTrackProjections()
{
var options = new DbContextOptionsBuilder<MovieContext>()
.UseInMemoryDatabase(databaseName: "MovieDB")
.Options;
// 0. Saving two movies
using (var context = new MovieContext(options))
{
context.Movies.AddRange(
new Movie { Name = "Matrix", ReleaseYear = 1999 },
new Movie {Name = "Titanic", ReleaseYear = 1997 }
);
context.SaveChanges();
}
// 1. Using a custom projection
using (var context = new MovieContext(options))
{
var firstMovieNameAndReleaseYear
= context.Movies
.Where(m => m.ReleaseYear >= 1990)
.Select(m => new { m.Name, m.ReleaseYear })
// ^^^^
// This is a custom projection
.First();
var noTracking = context.ChangeTracker.Entries();
Assert.AreEqual(0, noTracking.Count());
// ^^^
// No entities tracked
}
// 2. Using AsNoTracking
using (var context = new MovieContext(options))
{
var firstMovieWithNoTracking
= context.Movies
.Where(m => m.ReleaseYear >= 1990)
.AsNoTracking()
// ^^^^^
.First();
var withAsNoTracking = context.ChangeTracker.Entries();
Assert.AreEqual(0, withAsNoTracking.Count());
// ^^^
// As imply by its name, no entities tracked here
}
// 3. Retrieving a Movie
using (var context = new MovieContext(options))
{
var firstMovie = context.Movies
.Where(m => m.ReleaseYear >= 1990)
.First();
var beingTracked = context.ChangeTracker.Entries();
Assert.AreEqual(1, beingTracked.Count());
// ^^^
// Since we're retrieving only one Movie, tracking happens here
}
}
}
Only when we queried the first movie without a projection and without .AsNoTracking()
, Entity Framework Core tracked the underlying entity.
Et voilà!
For more tricks with Entity Framework Core, read how to configure default values for nullable columns with default constraints.
10 Jun 2025 #misc
In 2018, I wrote my first words online.
I had no idea what to do and how to do it. I just Googled how to get better at coding and found “start a blog.”
After procrastinating for a couple of days, choosing a name and a theme for my blog, I dumped a bunch of words into a file and hit Publish.
After years of trial and error, my analytics grew from 10 visitors a month to 1,000 visitors and I made my first $100 by pure luck.
But if I had to start all over again, here are 10 actions I’d take:
1. Think of my online presence as a business
Writing online was just something cool I did on the side of my 9-to-5.
For so long, I only thought my online presence would make me appear “attractive” to recruiters and hiring managers. I didn’t know our online presence is our most valuable asset.
Our personal brand is our own one-person business.
2. Start on a social blog like Medium or Quora
I started a blog because it was the only free advice I found.
But the thing with blogs is that our content is at the mercy of search engines, SEO, and their bots. Social blogs have a “feed” and algorithm to match readers with content. And that’s the best way to get faster feedback as a writer.
As a coder, I’d start in a social blog like dev.to or Medium, sharing TIL posts.
I only started on LinkedIn 4 or 5 years after starting my blog.
And I only shared links to my posts, pretending to steal LinkedIn users for my blog. Instead, I’d use X or LinkedIn to test ideas, share nuggets of my long-form content, and grow a newsletter. Speaking of which…
4. Start a newsletter from day 1
Subscribers are the real metric to track. Not followers, likes, or comments.
They are our true fans. From day 1, I’d invite readers to join my newsletter at the end of every post and I’d email them weekly.
5. Use consistent user handles
Oh boy! I used to think hacker-like user handles, like Napster, Codemaestro, or Neo were cool.
Instead I’d use a more professional user handle across all platforms.
6. Go for volume first
I only wrote on my blog when I thought I had something to say.
That was once in a blue moon. And when I started on LinkedIn, that was once a week. It’s no surprise I only saw traction when I went for volume.
If I were to start again, I’d go with volume: 30 long-form pieces and at least 100 short-form posts to get the juices flowing.
7. Come up with a simple content plan
For so long, I only wrote when I had something to say. No content plan.
But to fix that, I’d send one or two long-form emails to my newsletter, and repurpose them into one daily short-form post every week. That’s the simple content plan from millionaire creators.
8. Find ways to monetize earlier: courses/ebooks/templates
Making money from my online presence was an afterthought. I didn’t even know I could make money online.
To start again, I’d come up with monetization strategies after the first or second month. For example, I’d package my best-performing content into an ebook or a course and put a price tag on it somewhere like Gumroad.
Those first few dollars would motivate me to keep creating and fund higher-quality products.
9. Only after #1-#8, buy a domain and start a website
I’ve built my presence on rented land. Ooops!
And when I tried to buy a domain under my name, it was already taken. It turns out there’s a famous soccer player, a singer, and a film director with my same first and last name. Arrggg!
I’d buy a domain name, even if I didn’t use it. Or to simply point to a landing page linking to my newsletter and my other accounts.
10. Invest in courses, training, and coaching
Six years passed before I bought my first writing course.
Of course, I had consumed a lot of YouTube content to learn about SEO and blog post writing. But those were only two skills I needed to learn to make my online presence a real business.
I’d invest more in education to save myself a lot of time and take all the money I was leaving on the table. Well, it’s never too late to start again and invest in our online presence and turn it into something real.
09 Jun 2025 #misc
What does being wealthy truly mean?
Yesterday, before starting 21 Lessons for the 21st Century, I watched a YouTube interview with Yuval Noah Harari about that book. That was part of my new reading strategy. Authors often go on podcast tours to promote their books, sharing their insights and the intentions behind their books.
Towards the end, the interview closed with this unexpected idea:
“If you’re important, you don’t have a phone. If you work for somebody else, you have a phone”
That was shocking but eye-opening. The point isn’t about owning a phone per se but about having full control of our time. A phone means your boss might interrupt you with any apparent urgent issue.
That line hit really hard. It was only after a layoff that I realized I felt the pressure of always being available and responding to messages. I didn’t know how a salary had messed with my mind.
True wealth isn’t measured in currency, but in the ability to own our time. And I need to dump my phone.
08 Jun 2025 #misc
What started as mindless scrolling on Medium yesterday turned into a writing exercise.
I decided to stop scrolling like a zombie and pay attention to the headlines I found. Then to practice my headline-writing muscles, I took a closer look at some posts, rewriting their headlines for clarity and curiosity. I wanted to follow a top Medium writer’s formula for engaging headlines.
Here are 5 headlines I found and my own version of them:
1. “Rethinking the Value of Doing Nothing”
This was a short story about a random walk in the park. An old man sitting on the grass made the author reflect on rest and productivity.
My version: “An Old Man Sitting in the Park Changed My Mind About Productivity”
2. “My Experience With ChatGPT”
My first thought when I found this headline was: why should I care? Who are you? What did you use ChatGPT for? This post was from a writer who tried ChatGPT to speed up her writing process.
My version: “I Hired ChatGPT as My Writing Intern—Here’s What I Learned”
3. “7 Things That Show You’re Making Progress”
Making progress in what? A video game? Business? This was a post about small signs of progress when nothing else seems to be working.
My version: “7 True Signs You’re Making Progress in Life (Even When Nothing Seems to Work)”
4. “The Beautiful Habit I’ve Picked Up Lately”
This headline needs more specificity. A habit for what? Health? Business? A habit to achieve what? What makes it beautiful? This was a post about starting meaningful conversations.
My version: “This Simple Habit Has Taught Me More About Human Connection (Than Any Self-Help Book)”
This was a post dissecting an email with the classic fake job listing scam. Its headline could benefit from more drama.
My version: “Ignore These 7 Signs and Fall Prey to Email Scammers Offering You Fake Jobs”
Clear headlines are better than clever ones. “On writing” or “On the value of consistency” doesn’t say anything about what we’ll find inside. I declare myself guilty, too. A headline isn’t just a title, it’s a promise. Make it crystal clear because a vague headlines means no readers.
07 Jun 2025 #writing
The hardest part of being a new writer isn’t writing, but writing when nobody is reading.
For me, it took me years before I saw my first 1,000 blog visitors. And when I revived my LinkedIn account in 2024, it took me over a year for my first post to finally go “viral.”
Those first months feel like shouting into the void. No likes, no comments, no followers. Nothing.
But to see results, we have to push through that phase. Here are 5 actions to try to keep showing up in those hard moments:
#1. Have a clear goal (or an anti-goal). Sometimes knowing what you don’t want is more powerful than knowing what you do want. For most of us, it’s the side gig that keeps us from going back to corporate cubicle.
#2. Join a community or find a buddy. It’s easier to keep showing up when there’s someone walking the same path next to you. Someone who encourages you and gives genuine feedback.
#3. Develop a habit. Find a time and place to practice your craft. And make the commitment to show up, even if that means staring at a blank page. Write or create for yourself, go for volume, and focus on improving your craft.
#4. Celebrate every small victory. Screenshot every extra like or new follower and revisit them when you feel like breaking the chain.
#5. Find someone to make proud or jealous. Or to prove wrong. From the E-Myth Revisited, entrepreneurs aren’t the ones who start most businesses, but frustrated employees. Maybe to prove to their boss that they could create a better business, or to make an ex jealous. Sometimes, the best motivator is hearing “You can’t do it” and proving them wrong.