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
Well, based on your scenario and description, while both
context.Routesandcontext.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.