I want do add my current DbContext to whatever Class I use, for the moment I'm just passing the _context like a common variable.
In this controller example I Pass the _context every time i want to create a Item
[HttpPost("receta/{id}")] [APIauth("medico")] public IActionResult PostItemsReceta(int id, [FromBody]Data[] items) { var tran = _context.Database.BeginTransaction(); //DBB transaction begins try { foreach (Data item in items) new Item(id, item, _context); //I pass the _context like this. tran.Commit(); return Ok(); } catch (Exception e) { tran.Rollback(); return BadRequest("Not inserted!!"); } } And in the Class Item I have this
public class Item { [Key] public int id { get; set; } public DateTime? fcaducidad { get; set; } public string nombre { get; set; } public Int32 diagnostico { get; set; } public Item() { } public Item (int receta, Data i, MyDbContext _context) { try { var q = $"EXEC ItemReceta_Insert @idItemFarmacia={i.itemFarmacia.id}" + $", @idDiagnostico={i.diagnostico}, @cantidad={i.cantidad}" + $", @receta={receta}, @posologia='{i.posologia}'"; _context.Database.ExecuteSqlCommand(q); } catch (Exception e) { throw new Exception("Error al insertar ItemReceta", e); } } public static Item[] Report( int receta, MyDbContext _context) { string q = $"EXEC Item_Report @receta={receta}"; return _context.Item.FromSql(q).ToArray(); } } I don't want just to have direct access to the context in the controllers because I'm using it many times, I want
new Item(id, item); Not
new Item(id, item, _context); Item.Report(bla, _context); new WhatEverClass(name, age, _context);