The choice between using the DbContext.Set or the DbSet object instantiated in the Context depends on the use and how you work with context.
The DbContext.Set<T>
method returns using the Generics DbSet of the context, evaluating the type parameter of the method signature. This demonstrates that when we call it, it performs a "lookup" on context objects and "loads" the data of that type into the Context.
The DbSet<T>
object of the Context is an object that in theory is loaded when you instantiate the Context and this object is preloaded for use within the application.
The two methods do pretty much the same thing, but at different times. Another factor that can influence the use of one or the other is the exposure of objects between different libraries and namespaces. If you pass your context to a method using the DbContext class in the statement of this method, you are not aware of the context DbSets, so the way to load the data is by using the generic DbSet. Here is a small example:
using System;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Collections.Generic;
public class Contexto : DbContext
{
public DbSet<Aluno> Alunos { get; set; }
public Contexto()
{
Configuration.LazyLoadingEnabled = true;
Configuration.AutoDetectChangesEnabled = false;
Configuration.ValidateOnSaveEnabled = false;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
}
}
public class Aluno
{
public String Nome { get; set; }
}
public class Program
{
public List<Aluno> GetAlunos(DbContext ctx)
{
// O compilador não irá reconhecer se chamarmos o DbSet ctx.Alunos.
return ctx.Set<Aluno>().ToList();
}
public List<Aluno> GetAlunos2(Contexto ctx)
{
return ctx.Alunos.ToList();
}
}