2016-06-21 3 views
1

나는 그것에 60 개의 다른 문자열을 가진 클래스가 있습니다. 하나의 이름을 가진 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

당신은 속성 클래스를 사용할 수 있습니다 typeof(contact).GetProperties()를 사용 contact의 속성을 통해

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

그리고 루프를, PropertyInfo.GetCustomAttributes()를 사용하여 속성을 찾아 다음 PropertyInfo.SetValue()를 사용하여 값을 얻을 PropertyInfo.GetValue()를 사용하여 값을 설정합니다.

관련 문제