forum

Home / DeveloperSection / Forums / How can I extend an API controller to hold a variable for my database Context?

How can I extend an API controller to hold a variable for my database Context?

Anonymous User 2346 26-Jan-2015

I have many classes like this one. They all have two things in common. They declare a private variable called Context and they have a method to dipose of that.

Is there a way I can create an intermediate class that I could inherit from that has the code to declare the variable and the dispose method? I assume it's easy to do but I am not sure how to declare the variables and the method. Should they be private?

public class TypeController : ApiController
{
    private Context db = new Context();
 
    [Route("GetMapData")]
    public async Task<IHttpActionResult> GetMapData()
    {
        var result = await db.Types
                             .Select(e => new
                             {
                                 Id = e.TypeId,
                                 Name = e.Name
                             })
                             .ToListAsync();
        return Ok(result);
    }
 
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
 
}

 


Updated on 27-Jan-2015
I am a content writter !

Can you answer this question?


Answer

1 Answers

Liked By