ラブびあ

ビール。ときどきラブ

Entityに値をコピーする

Entityクラスに、引数で渡されたEntityのプロパティ値をコピーするAssignメソッドを実装してみました。引数のEntityから自分のプロパティと同じ名前のプロパティを探して値をgetし、自分のプロパティにsetするだけのシンプルな機能です。

public void Assign(Entity e)
{
    if (e == null)
    {
        return;
    }

    Type et = e.GetType();

    foreach (var p in this.GetType().GetProperties())
    {
        PropertyInfo ep = et.GetProperty(p.Name);
        if (ep == null)
        {
            continue;
        }

        object ev = ep.GetValue(e, null);
        if (ev != null)
        {
            ev = Convert.ChangeType(ev, Nullable.GetUnderlyingType(p.PropertyType) ?? p.PropertyType);
        }
        p.SetValue(this, ev , null);
    }
}


ASP.NETでListViewを使っていて、ListView.ItemsからFindControlする処理で、同じ感じ?で、引数で渡されたListViewItemからコピーするAssignメソッドです。このメソッドでコピーできるようにするには、Entityのプロパティ名とaspのコントロール名を同じ名前にする必要があります。

つまり、Entityのhogeプロパティをバインドするaspコントロールhoge

<asp:Label ID="hoge" runat="Server" Text='<%# Eval(Container.DataItem, "hoge") %>' />
public void Assign(ListViewItem item)
{
    foreach (var p in this.GetType().GetProperties())
    {
        object o = item.FindControl(p.Name);
        if (o == null)
        {
            continue;
        }

        Type up = Nullable.GetUnderlyingType(p.PropertyType);

        if (o is ITextControl)
        {
            //""(入力なし)をstringプロパティまたはNullableプロパティにセットするときはnullをセットする
            if (string.IsNullOrEmpty((o as ITextControl).Text))
            {
                if (p.PropertyType.Equals(typeof(string)) || up != null)
                {
                    p.SetValue(this, null, null);
                    continue;
                }
            }

            p.SetValue(this, Convert.ChangeType((o as ITextControl).Text, up ?? p.PropertyType), null);
            continue;
        }

        if (o is ICheckBoxControl)
        {
            p.SetValue(this, Convert.ChangeType((o as ICheckBoxControl).Checked, up ?? p.PropertyType), null);
            continue;
        }
    }
}