2016-06-21 3 views
1

私は60の異なる文字列を持つクラスを持っています。私は彼らが1つの名前を持っているAPIから文字列をフェッチし、それらを保存し、別の名前を持つデータベースに挿入する必要があります。クラス値の長いリストを設定するC#の整頓方法?

だから私のコードでは、60の

var data = (from l in resultsxml.Root.Descendants(ns + "contacts").Elements(ns + "contact") 
select new contact { 
id        = (string)l.Element("id").Value, 
surname       = (string)l.Element("lastName").Value, 
companyName      = (string)l.Element("organisationName").Value, 
... 

のようなコードの行、その後、別の60本の

cmd.Parameters(new SqlParameter("@LastName", i.surname)); 
cmd.Parameters(new SqlParameter("@DivisionName", i.companyName)); 
... 

のような線としてだけでなく、クラス宣言は、現在あります。

私は60文字列をループし、クラスに名前情報を格納できるので、これを書くためのちょっとした方法がありますか?

+0

'Xml'自体をパラメータとして渡して、データベース内でマッピング(論理)を実行するのは良いことではないでしょうか? –

答えて

0

あなたは属性クラスを使用することができます。

public class ElementAndParamNameAttribute : Attribute 
{ 
    public string Element {get;set;} 
    public string Param {get;set;} 
} 
. 
. 
. 
public class contact 
{ 
    [ElementAndParamNameAttribute(Element="lastName",Param="@lastName")] 
    public string surname {get;set;} 
    . 
    . 
    . 
} 

そしてtypeof(contact).GetProperties()を使用してcontactのプロパティをループ、PropertyInfo.GetCustomAttributes()を使用して属性を見つけ、PropertyInfo.SetValue()を使用して値を取得し、その後PropertyInfo.GetValue()を使用して値を設定します。

関連する問題