I want to expand on the question below:
How to instantiate a DbContext in EF Core
I've done the above in my controller, but am now trying to create DataAccess.cs where I want all my database methods/queries to happen. For example, I have the following so far:
Controller:
public class HomeController : Controller
{
DataAccess da = new DataAccess() { };
private readonly DatabaseContext db;
public HomeController(DatabaseContext reg)
{
db = reg;
}
[HttpPost, ValidateAntiForgeryToken]
public IActionResult Register(User model)
{
model.WindowsAuth = User.Identity.Name;
if (ModelState.IsValid)
{
da.Registration(model, db);
return RedirectToAction("Index");
}
In DataAccess.cs
public class DataAccess
{
public void Registration(User model, DatabaseContext db)
{
User newUser = new User();
db.Users.Add(model);
db.SaveChanges();
}
}
Database context
public class DatabaseContext :DbContext
{
public DatabaseContext(DbContextOptions<DatabaseContext> options)
: base(options)
{
}
public DbSet<User> Users { get; set; }
}
The above works, but I want to add more methods into DataAccess.cs. Will I need to pass my database as a parameter from the controller everytime? The db variable comes out as null when I try to instantiate the context class in my data access class. I am new to MVC, so any further reading or sources related to this would be appreciated.
With the help of DI you should inject DataAccess
to controller and DatabaseContext
to DataAccess
. Also don't forget to register DataAccess
at DI container:
public class HomeController : Controller
{
private readonly DataAccess da;// = new DataAccess() { };
//private readonly DatabaseContext db;
public HomeController(DataAccess da)
{
this.da = da;
}
}
public class DataAccess
{
private readonly DatabaseContext db;
public DataAccess(DatabaseContext db)
{
this.db = db;
}
public void Registration(User model/*, DatabaseContext db*/)
{
User newUser = new User();
db.Users.Add(model);
db.SaveChanges();
}
}