Click here to Skip to main content
15,886,788 members
Articles / Web Development / ASP.NET
Tip/Trick

Dynamic ASP.NET Web API Controller - Part 1. Dynamic DTO

Rate me:
Please Sign up or sign in to vote.
4.95/5 (12 votes)
8 Jun 2016CPOL 39.6K   21   4
How to make dynamic DTO with ExpandoObject

Introduction

In this article, I'll introduce how to make dynamic DTO.

We don't need to make new DTO every time when you add new stored procedures. I will show how to make DTO dynamically using ExpandoObject class.

Background

Making DTO is somewhat annoying to me. So I utilize ExpandoObject class to make DTO dynamically.

Using the code

GitHub ; https://github.com/thinkit-software/WebProjects/tree/master/src/Common

This is my data access layer. I write this sample with enterprise library 6. After fetching data from databse, we can make DTO like  javascript's object. This means we can add new property to C# class in runtime. That's so amazing!

C#
namespace DavidJLee.DAL
{
    public class QueryExecutor
    {
        private readonly Database _db = default(Database);

        private static readonly Lazy<QueryExecutor> _instance = new Lazy<QueryExecutor>(() =>
        {
            return new QueryExecutor();
        });

        public static QueryExecutor Instance { get { return _instance.Value; } }

        public QueryExecutor()
        {
            DatabaseProviderFactory providerFactory = new DatabaseProviderFactory();
            DatabaseFactory.SetDatabaseProviderFactory(providerFactory, false);
            _db = DatabaseFactory.CreateDatabase();
        }

        public IEnumerable<dynamic> ExecuteStoredProcedure(string procName)
        {
            using (var command = _db.GetStoredProcCommand(procName))
            {
                var dataSet = _db.ExecuteDataSet(command);

                foreach (DataTable table in dataSet.Tables)
                {
                    foreach (DataRow row in table.Rows)
                    {
                        ExpandoObject dynamicDto = new ExpandoObject();

                        foreach (DataColumn column in table.Columns)
                        {
                            //With expandobject class, we can add new property like javascript's way.                           
                            ((IDictionary<String, Object>)dynamicDto).Add(column.ColumnName, row[column.ColumnName]);
                        }

                        yield return dynamicDto;
                    }                   
                }
            }
        }
    }

I use this method with ASP.NET Web API.

C#
namespace DavidJLee.DynamicWebAPI.Controllers
{   
    public class ValuesController : ApiController
    {
        // GET api/values
        public IHttpActionResult Get()
        {
            return Json<IEnumerable<object>>(QueryExecutor.Instance.ExecuteStoredProcedure("usp_User_GetList"));
        }      
    }
}

I try to call this web API with fiddler.

Request
GET http://localhost:50951/api/values HTTP/1.1
User-Agent: Fiddler
Host: localhost:50951


Response

Points of Interest

With this way, I developed dynamic Web API middle ware. Whenever I develop select command procedure, I don't need to add new controllers or actions. I just need to configure about new procedure (procedure name, parameter info etc).

History

1. Explanation of basic concept of dynamic web API with dynamic DTO (2014-08-23).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Nexon Korea
Korea (Republic of) Korea (Republic of)
I am a web developer in South Korea. I work at Nexon Korea now.

My interest:
- ASP.NET (MVC, Web API)
- C#
- Etc.

GitHub : https://github.com/thinkit-software

Comments and Discussions

 
GeneralExcellent Pin
Eka26-Aug-14 21:22
Eka26-Aug-14 21:22 
GeneralRe: Excellent Pin
David Lee 14526-Aug-14 22:39
professionalDavid Lee 14526-Aug-14 22:39 
GeneralNice, but... Pin
Pawel Cioch26-Aug-14 8:08
Pawel Cioch26-Aug-14 8:08 
GeneralRe: Nice, but... Pin
David Lee 14526-Aug-14 12:13
professionalDavid Lee 14526-Aug-14 12:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.