Ehi
Ehi

Reputation: 57

ASP.NET Core 2 - How to call and manipulate a Database class from a controller

I am using ASP.NET Core 2 and I have a controller that runs Tasks.
For example, the one below does a simple file upload, I have others that run other Tasks or Actions and I want to be able to log the events or tasks into my database.

So I need to create a class to run INSERTs or UPDATEs on a database.

How do I create a class that does my database manipulation either using DbContext or call a stored procedure using a class (and not a controller)?

Here is a sample of one of my controller's code:

public async Task<IActionResult> Uploads(string fullName, IFormFile pic)
{
  try { 
    string user = null;
    try
    {
      user = User.Identity.Name.ToString();
    }
    catch (Exception err)
    {
      user = "anonymous";
    }
    if (user == null)
    {
      user = "";
    }
    string path = he.WebRootPath + "/uploads/" + user ;

    if (!Directory.Exists(path))
    {
      Directory.CreateDirectory(path);
    }

    DateTime date = DateTime.Now ;
    var dates = date.ToLongDateString();
    var ext = Path.GetExtension(path).ToLowerInvariant();
    var fileName = Path.Combine(he.WebRootPath + "/uploads/" + "/" + user, Path.GetFileName(pic.FileName));
    var f = Path.Combine(he.WebRootPath + "/uploads/" + "/" + user,  dates+Path.GetFileName(pic.FileName));
    int i = 0;
    ViewData["fname"] = fullName;
    if (pic != null || pic.Length == 0)
    {
      using (var stream = new FileStream(fileName, FileMode.Create))
      {
        await pic.CopyToAsync(stream);
      }
      ViewData["fileLocation"] = "/uploads/" + user + "/" + Path.GetFileName(pic.FileName);
//  }
}

Upvotes: 0

Views: 485

Answers (1)

M&#233;toule
M&#233;toule

Reputation: 14472

You can use dependency injection to inject your DbContext into your controller:

public class MyController : Controller
{
    private readonly DbContext _db;
    public MyController(DbContext db)
    {
        _db = db;
    }

    public async Task<IActionResult> Uploads(string fullName, IFormFile pic)
    {
        _db.ExecuteSql("INSERT ...");
    }
}

Once you have your Db context, you can do what you need with it.

Upvotes: 1

Related Questions