Czy da się poprzez konstruktor wstrzyknąć obiekt MyEfContext
do klasy AddStudentViewModel
podczas bindowania modelu? Jeśli nie, to w jaki sposób najlepiej otrzymać kontekst bazy danych w metodzie IsValid()
?
Controller
public class StudentController : Controller
{
[HttpPost]
public IActionResult Add(AddStudentViewModel vm)
{
if (!ModelState.IsValid || !vm.IsValid())
{
return View();
}
//add student
return RedirectToAction("Index");
}
}
ViewModel
public class AddStudentViewModel
{
private MyEfContext _context;
public AddStudentViewModel()
{
}
public AddStudentViewModel(MyEfContext context)
{
_context = context;
}
public string UniqueName { get; set; }
public int Age{ get; set; }
public bool IsValid()
{
if (_context.Students.Any(x => x.UniqueName == UniqueName))
{
return false;
}
return true;
}
}