Get property [key] from ViewModel

I have a ViewModel that has a [key] property, and I would like to get this from an instance of this view model.

My code looks something like this (fictional models)

 class AddressViewModel { [Key] [ScaffoldColumn(false)] public int UserID { get; set; } // Foreignkey to UserViewModel } // ... somewhere else i do: var addressModel = new AddressViewModel(); addressModel.HowToGetTheKey..?? 

So I need to get the UserID (in this case) from the ViewModel. How can i do this?

+4
source share
2 answers

If you are stuck or confused with any of the code in the example, just release the comment and I will try to help.

In general, you are interested in using Reflection to traverse type metadata to get properties that are assigned a given attribute.

Below is just one way to do this (there are many others, as well as many methods that provide similar functionality).

Taken from this question I contacted in the comments:

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

As John says, process multiple KeyAttribute declarations to avoid problems. This code also assumes that you are decorating public properties (non, non-public properties or fields) and require System.Reflection .

+7
source

You can use reflection to achieve this:

  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); } 
+2
source

Source: https://habr.com/ru/post/1439112/


All Articles