The choice between using the method Dbcontext.Set or the object Dbset instantiated in Context depends on the use and how you work with the context.
The method DbContext.Set<T>
returns using Generics the Dbset of the context, evaluating the method signature type parameter. This demonstrates that when we call it, it performs a "search" on the context objects and "loads" the data of that type within Context.
The object DbSet<T>
Context is an object that in thesis is loaded when you instance Context and this object is preloaded for use within the application.
The two methods do practically 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 enunciation of this method, you are not aware of the context Dbsets, so the way to load the data is by using generic Dbset. Below 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();
}
}
Cigado, but wasn’t the T set with a specific type to be used? As in the example you gave, T expects a class that can be Student or Teacher?
– Kelly Soares
You can limit
T
using a syntax like this:public IEnumerable<T> PrimeirosDez<T>() where T: class, IMinhaInterface { ... }
– Leonel Sanches da Silva