Repository Pattern Retrieve Desired Columns Only

拥有回忆 提交于 2019-12-04 14:12:19

This is kind of a long answer but here is an extension method I created for doing this. I am returning an object in this case because this is used in webAPI to just return json and I do not need a particular type but this can easily be adapted to return a generic entity type.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json.Linq;

namespace Your.Extensions
{
    public enum PropertyFormat
    {
        AsIs,
        PascalCase,
        CamelCase
    }

    public static class DataShapingExtensions
    {
        public static object ToDataShape<ObjectIn>(this ObjectIn objectToShape, string fields, PropertyFormat propertyFormat = PropertyFormat.AsIs) where ObjectIn : class
        {
            var listOfFields = new List<string>();

            if (!string.IsNullOrWhiteSpace(fields))
            {
                listOfFields = fields.ToLower().Split(',').ToList();
            }

            if (listOfFields.Any())
            {
                var objectToReturn = new JObject();

                //====
                var enumerable = objectToShape as IEnumerable;

                if (enumerable != null)
                {
                    var listOfObjects = new List<JObject>();

                    foreach (var item in enumerable)
                    {
                        var objectToReturn2 = new JObject();

                        listOfFields.ForEach(field =>
                        {
                            try
                            {
                                var prop = item.GetType()
                                    .GetProperty(field, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

                                var fieldName = prop.Name;
                                var fieldValue = prop.GetValue(item, null);

                                fieldName = GetName(fieldName, propertyFormat);
                                objectToReturn2.Add(new JProperty(fieldName, fieldValue));
                            }
                            catch (Exception ex) { }
                        });

                        listOfObjects.Add(objectToReturn2);
                    }

                    return listOfObjects.ConvertAll(o => o);
                }
                //====

                listOfFields.ForEach(field =>
                {
                    try
                    {
                        var prop = objectToShape.GetType()
                            .GetProperty(field, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

                        var fieldName = prop.Name;
                        var fieldValue = prop.GetValue(objectToShape, null);

                        fieldName = GetName(fieldName, propertyFormat);
                        objectToReturn.Add(new JProperty(fieldName, fieldValue));
                    }
                    catch (Exception ex) { }
                });

                return objectToReturn;
            }

            return objectToShape;
        }

        private static string GetName(string field, PropertyFormat propertyFormat)
        {
            switch (propertyFormat)
            {
                case PropertyFormat.AsIs: return field;
                case PropertyFormat.PascalCase: return field.ToPascalCase();
                case PropertyFormat.CamelCase: return field.ToCamelCase();
                default: return field;
            }
        }
    }
}

//Usage

[HttpGet, Route("api/someroute")]
public async Task<IHttpActionResult> YourMethod(string fields = null)
{
    try
    {
         var products = await yourRepo.GetProductsList();

         if (fields.HasValue())
         {
              return Ok(products.ToDataShape(fields, PropertyFormat.CamelCase));
         }

         return Ok(products);
     }
     catch (Exception)
     {
         return InternalServerError();
     }
}

//Call route

/api/someroute?fields=productID,productName

//output (json)

{
    productID: 1,
    productName: "Some Name"
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!