2

In my ASP .Net Web API Application while making the DB calls, some properties are needed to be added to the Model Class which already have some existing properties.

I understand I can use ExpandoObject in this case and add properties at run time, but I want to know how first to inherit all the properties from an existing object and then add a few.

Suppose for example, the object that's being passed to the method is ConstituentNameInput and is defined as

public class ConstituentNameInput
{
    public string RequestType { get; set; }
    public Int32 MasterID { get; set; }
    public string UserName { get; set; }
    public string ConstType { get; set; }
    public string Notes { get; set; }
    public int    CaseNumber { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public string PrefixName { get; set; }
    public string SuffixName { get; set; }
    public string NickName { get; set; }
    public string MaidenName { get; set; }
    public string FullName { get; set; }
}

Now in my dynamically created object I want to add all these existing properties and then add a few named wherePartClause and selectPartClause.

How would I do that ?

2
  • Please use formatting considerately - there's no point in putting a whole non-code paragraph in the form of code. Commented Apr 18, 2016 at 6:04
  • Sorry .. it was my fault. Going forward I will take care of it. Commented Apr 18, 2016 at 6:11

1 Answer 1

14

Well you could just create a new ExpandoObject and use reflection to populate it with the properties from the existing object:

using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Reflection;

class Program
{
    static void Main(string[] args)
    {
        var obj = new { Foo = "Fred", Bar = "Baz" };
        dynamic d = CreateExpandoFromObject(obj);
        d.Other = "Hello";
        Console.WriteLine(d.Foo);   // Copied
        Console.WriteLine(d.Other); // Newly added
    }

    static ExpandoObject CreateExpandoFromObject(object source)
    {
        var result = new ExpandoObject();
        IDictionary<string, object> dictionary = result;
        foreach (var property in source
            .GetType()
            .GetProperties()
            .Where(p => p.CanRead && p.GetMethod.IsPublic))
        {
            dictionary[property.Name] = property.GetValue(source, null);
        }
        return result;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.