2012-10-11 4 views
4

나는 [key] 속성을 가진 ViewModel을 가지고 있는데 그 뷰 모델의 인스턴스에서 가져오고 싶습니다.ViewModel에서 [key] 속성 가져 오기

내 코드

class AddressViewModel 
{ 
    [Key] 
    [ScaffoldColumn(false)] 
    public int UserID { get; set; } // Foreignkey to UserViewModel 
} 

// ... somewhere else i do: 
var addressModel = new AddressViewModel(); 
addressModel.HowToGetTheKey..?? 

그래서 내가 뷰 모델에서 UserID (이 경우)를 취득하기 위해 필요한이 (가상 모델)과 같이 보입니다. 내가 어떻게 할 수 있니?

+1

. [이 질문] (http://stackoverflow.com/questions/390594/c-sharp-setting-property-values-through-reflection-withattribute)에서는 주제를 다룹니다. –

+1

'KeyAttribute'가 여러 속성에 주석을 달면 어떤 일이 일어나는지 생각해 봐야합니다. – Jon

답변

6

예제의 코드 중 하나와 혼동 스럽거나 혼동 스러울 경우 주석을 달아 주시면 도움을 드리겠습니다. 요약

, 당신은 지정된 속성이 그들에게 할당 한 특성을 얻을 수있는 유형의 메타 데이터를 걸어 반사 사용에 흥미 있습니다.

아래는 단지 하나는입니다 (비슷한 기능을 제공하는 많은 다른 방법과 많은 방법이 있습니다).

내가 코멘트에 링크 된 this question에서 촬영 : 존 말한다처럼

PropertyInfo[] properties = viewModelInstance.GetType().GetProperties(); 

foreach (PropertyInfo property in properties) 
{ 
    var attribute = Attribute.GetCustomAttribute(property, typeof(KeyAttribute)) 
     as KeyAttribute; 

    if (attribute != null) // This property has a KeyAttribute 
    { 
     // Do something, to read from the property: 
     object val = property.GetValue(viewModelInstance); 
    } 
} 

이 문제를 방지하기 위해 여러 KeyAttribute 선언을 처리합니다. 또한이 코드는 public 속성 (비공개 속성이나 필드가 아님)을 장식한다고 가정하고 System.Reflection이 필요합니다. 당신이 이것을 달성하기 위해 반사를 사용할 수

+0

감사합니다. 작동 중입니다. :) – w00

2

:

당신은 KeyAttribute`가 존재`있는지 확인하기 위해 뷰 모델 인스턴스의 속성을 도보로 반사를 사용하여 각`PropertyInfo`의 사용자 지정 특성을 조회 할
 AddressViewModel avm = new AddressViewModel(); 
     Type t = avm.GetType(); 
     object value = null; 
     PropertyInfo keyProperty= null; 
     foreach (PropertyInfo pi in t.GetProperties()) 
      { 
      object[] attrs = pi.GetCustomAttributes(typeof(KeyAttribute), false); 
      if (attrs != null && attrs.Length == 1) 
       { 
       keyProperty = pi; 
       break; 
       } 
      } 
     if (keyProperty != null) 
      { 
      value = keyProperty.GetValue(avm, null); 
      }