c# - Add DbContext to all Classes not just controllers in .NET Core -


i want add current dbcontext whatever class use, moment i'm passing _context common variable.

in controller example pass _context every time want create 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 _context this.          tran.commit();         return ok();      } catch (exception e) {         tran.rollback();         return badrequest("not inserted!!");     }             } 

and in class item 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 have direct access context in controllers because i'm using many times, want

new item(id, item); 

not

new item(id, item, _context); item.report(bla, _context); new whateverclass(name, age, _context); 

i think aren't separating concerns, there's number of approaches this, i'll present simple approach getting things injected own classes (i'll leave out of properties in solution keep simple ). main thing need register class service. so..

first, make item poco

 public class item     {         public int id { get; set; }     } 

now put code related how trying put items in , out of database service, make constructor take dbcontext injected

public class itemservice  {     private readonly applicationcontext _context;      public itemservice(applicationcontext context)     {         _context = context;     }      public void add(item item)     {         // paramatized query of sort prevent sql injection         // see https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/advanced         var parameters = new list<object>();         _context.database.executesqlcommand("", parameters);     } } 

now, configure services add item service

public void configureservices(iservicecollection services)         {             services.adddbcontext<applicationcontext>();             services.addscoped<itemservice>();                  } 

now in controllers constructor want service,

private readonly itemservice _itemservice public myfancypantscontroller(itemservice itemservice) {   _itemservice = itemservice; } 

now on post can access service

 [route("post")]     [httppost()]             public iactionresult postitem()     {         // construct / deserialize items, add them...         _itemservice.add(new item());         return ok();     } 

now....you may find have lot of entities ( item ) , creating services them pita, may want more generic repository service.


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -