Deepening my knowledge in ASP.NET, I have a question that arises from the following class:
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<Route> Routes { get; set; }
}
What is the difference under the hood between using context.Routes
and using context.Set<Route>()
?
I verified that the two instances are not equal in the following way
Console.WriteLine(context.Routes.Equals(context.Set<Route>()))
I checked here but I still haven’t resolved my question.
Thanks in advance
2
Answers
You have
And you can call it any time like
But what if you have some generic code?
In other words, this is different because in the first case you use a concrete implementation and in the second case you’re flexible and can use different implementations of Context.
"What is the difference under the hood between using…"
Under the hood only one difference.
Set<T>()
dynamically finds property of the concrete instance and makes call against that. You can see implementation yourself if you use a tool likedotPeek
Well, based on your scenario and description, while both
context.Routes
andcontext.Set<Route>()
access Route entities, they differ in their nature and purpose. First of all, context.Routes is a single, persistent collection within the context, tracking changes for saving. On the other hand,context.Set<Route>()
creates temporary sets for specific operations, not affecting the main collection or tracking changes. Choose context.Routes for general interactions and persistence, andcontext.Set<Route>()
for temporary queries without modifying the main collection.Therefore, if you need to work with entity types dynamically or if you have a reference to the entity type as a Type object, then
context.Set<TEntity>()
might be more appropriate.Note: In addition, you could refer to this official document for more explanation.