Search code examples
asp.netasp.net-coreasp.net-web-apidbcontextdbset

What are the differences between calling context.Users and context.Set<User>?


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


Solution

  • What are the differences between calling context.Users and context.Set?

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