1
In ASP.NET Core Mvc I can access Dbcontext in the Controller through the property _context
represented by my class MvcNotaContext
see:
private readonly MvcNotaContext _context;
This way I can perform a database search 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 the validation, but, I don’t know how I could get an instance of my class MvcNotaContext
directly in my model class Nota
, and this class requires configuration options DbContextOptions<MvcNotaContext> options
to function, being that it is used in the method ConfigureServices
in class Startup
initialization:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<MvcNotaContext>(options => options.UseSqlite("Data Source=MvcNota.db"));
}
My model 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 bank would occur in the method Validate
, respectively.
Question
How can I access the database directly from my model class (model) in an ASP.NET Core Mvc project?
I didn’t understand it very well. The Note class is a model or an entity?
– Gabriel Coletta
You can consider as a Model.
– gato
If it is a model, I can consider that you are using as a Viewmodel next to Razor?
– Gabriel Coletta
In this case it is not a Viewmodel, it is only the Model that represents the note table in my database.
– gato
It is this class that you use in your Dbset to configure your database?
– Gabriel Coletta
Yes exactly, just this class. The bank is just a table.
– gato