I have a ViewModel which has a [key]
property and i would like to get that from an instance of that 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?
You can use reflection to achieve this:
If you are stuck or confused with any of the code in the example, just drop a comment and I'll try to help.
In summary, you are interesting in using Reflection to walk the meta-data of the type to get properties that have a given attribute assigned to them.
Below is just one way of doing this (there are many others and also many methods that provide similar functionality).
Taken from this question I linked in the comments:
Like Jon says, handle multiple
KeyAttribute
declarations to avoid issues. This code also assumes you are decoratingpublic
properties (not, non-public properties or fields) and requiresSystem.Reflection
.