skip to Main Content

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


  1. You have

    public class AppDbContext : DbContext
    {
        public DbSet<Route> Routes { get; set; }
    }
    

    And you can call it any time like

    var ctx = new AppDbContext();
    var list = ctx.Routes.Where(....);
    

    But what if you have some generic code?

    public void DoSomething<T>(DbContext ctx)
    {
        var list = ctx.Set<T>().Where(...);
    }
    

    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 like dotPeek

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search