mardi 12 juillet 2016

How to implement repository pattern with anonymous types WEB API 2

We are using EF6 data first approach to create REST based API's which are consumed by various clients(like IOS, web app, andriod etc).Below is the sample code of one of web api method in a web api 2 controller:

 [HttpGet]
        [Route("companies")]
        public HttpResponseMessage RetrieveAnnuityCompanies()
        {
            var db = new TestEntities();
            var annuityCompany = from company in db.Company
                                 where company.IsExcluded == false
                                 orderby company.CompanyName
                                 select new
                                 {
                                     companyId = company.CompanyId,
                                     companyName = company.CompanyName
                                 };

            string json = JsonConvert.SerializeObject(annuityCompany);
            var response = this.Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return response;
        }

Like above API methods we have multiple API's method in different controllers.Now we want to reuse some of our data access logic in other controllers but by directly putting data access code in controller code its not possible with current approach. We are planning to use repository pattern but the problem which we are facing is that if move data access code to some other repository class then we have to create classes for each of anonymous type result like annuityCompany in above example which will waste a lot of time.

Please suggest how can we solve this by reusing our existing stuff and implement the pattern.

Aucun commentaire:

Enregistrer un commentaire