In ASP.NET Core Mvc I get access to DbContext on the Controller through the _context
property represented by my MvcNotaContext
class see:
private readonly MvcNotaContext _context;
This way I can search the database in the controller class:
var nota = await _context.Nota.SingleOrDefaultAsync(m => m.ID == id);
However, I have a business rule in my model that needs to get some data directly from the database to perform validation, but I'm not sure how I could get an instance of my MvcNotaContext
class directly in my class Nota
, and this class needs the DbContextOptions<MvcNotaContext> options
configuration options to work, and it is used in the ConfigureServices
method in the Startup
startup class:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<MvcNotaContext>(options => options.UseSqlite("Data Source=MvcNota.db"));
}
My template class:
public class Nota: IValidatableObject
{
public int ID { get; set; }
[Required(ErrorMessage="Titulo não pode ficar vazio.")]
[DataType(DataType.Text)]
[Display(Name="Título")]
public string Titulo { get; set; }
[Required(ErrorMessage="Conteúdo não pode ficar vazio.")]
[Display(Name="Conteúdo")]
[DataType(DataType.MultilineText)]
public string Conteudo { get; set;}
IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
//Busca dados na base de dados.
throw new System.NotImplementedException();
}
}
Access to the database would occur in the Validate
method, respectively.
Question
How can I access the database directly from my model class in an ASP.NET Core MVC project?