2016-04-18 9 views
2

DB呼び出し中にASP .Net Web APIアプリケーションで既存のプロパティが既に存在するModelクラスにいくつかのプロパティを追加する必要があります。C#の既存の静的オブジェクトからオブジェクトに動的にプロパティを追加する

私はこの場合にはExpandoObjectを使用し、実行時にプロパティを追加することができますが、既存のオブジェクトからすべてのプロパティを継承し、いくつか追加する方法を知りたいと思います。

は、たとえば、メソッドに渡されていたオブジェクトがConstituentNameInputであると私は、これらすべての既存のプロパティを追加し、名前のいくつかを追加したい私の動的に作成されたオブジェクトに今

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; } 
} 

として定義されているとwherePartClauseおよびselectPartClause

どうすればいいですか?

+0

思いやりの書式を使用してください - 全体非コード段落を置くことにはポイントはありませんコードの形式。 –

+0

申し訳ありません..それは私のせいでした。私はそれを世話するつもりです。 – StrugglingCoder

答えて

12

さて、あなただけの既存のオブジェクトからプロパティを移入するための新しいExpandoObjectと使用反射を作成することができます。

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; 
    } 
} 
関連する問題