1

I have a model

     public class Application : BaseModel, IApplication
     {
       [Key]
       public int ApplicationId { get; set; }

       public DateTime? Date { get; set; }

       public string ApplicationTypeId { get; set; }

       public List<AlternateSigningAuthority> AlternateSigningAuthorities { get; set; }

       public List<Land> Lands { get; set; }

     }

And another model

     public class Land : BaseModel, IEquatable<Land>/*, ILand*/
    {

       [Key]
        public int LandId { get; set; }

       [ForeignKey("ApplicationId")]
        public int ApplicationId { get; set; }

        public int Unit { get; set; }
    }

Similary I have a model for AlternateSigningAuthority. I want to get Primary Keys of these models.

I have code which works for Application

           var type = typeof(Application);
           var properties = type.GetProperties();

           var property = properties
                .FirstOrDefault(p => p.GetCustomAttributes(false)
                    .Any(a => a.GetType() == typeof(KeyAttribute)));

            if (property != null)
            {
                string msg = "The Primary Key for the {0} class is the {1} property";
                Console.WriteLine(msg, type.Name, property.Name);
            }

AS soon as I add

    foreach (var prop in properties)
        {
            var attributes = property.GetCustomAttributes(false);
            foreach (var attribute in attributes)
            {
                if (attribute.GetType() == typeof(KeyAttribute))
                {
                    string msg = "The Primary Key for the {0} class is the {1} property";
                    Console.WriteLine(msg, type.Name, attribute.ToString());
                }
            }

I dont get Primary keys. I want to use Application Model to get keys for other models.

Tina
  • 89
  • 1
  • 11
  • *Which* `Application` do you seach for `Key`? Can you be confused with this one: https://msdn.microsoft.com/en-us/library/system.windows.application(v=vs.110).aspx – Dmitry Bychenko Nov 03 '17 at 15:12
  • Possible duplicate of [Get \[key\] property from ViewModel](https://stackoverflow.com/questions/12835926/get-key-property-from-viewmodel) – Peter Szekeli Nov 03 '17 at 15:12
  • @Szeki- I went through the link you posted before posting this question. Actually I am trying to get keys for all the models through one. – Tina Nov 03 '17 at 16:01
  • @DmitryBychenko- I have application model which has values and I am going to use those values to fetch me keys.So basically Application will go through its properties and get me the LandId and similarly key from Alternate Signing Authority – Tina Nov 03 '17 at 16:17

3 Answers3

4

You just need to call Attribute.GetCustomAttribute

AddressViewModel viewModelInstance=new AddressViewModel();
        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);
            }
        }

I referred this link Get [key] property from ViewModel

Thanigainathan
  • 1,505
  • 14
  • 25
  • I did check that post. My code is complaining at Attribute.GetCustomAttribute as Attribute doesnt have definition for GetCustomAttribute. So i broke the line as var attribute= property.GetCustomAttributes(false); if (attribute.GetType() == typeof(KeyAttribute)) , but doesnt seem to be working. – Tina Nov 03 '17 at 16:09
1
public void WriteKeyProperty(Type classType)
{
    var properties = classType.GetProperties();
    foreach (var property in properties)
    {
        var keyAttribute = property.GetCustomAttribute(typeof(KeyAttribute));
        if (keyAttribute == null) continue;
        const string msg = "The Primary Key for the {0} class is the {1} property";
        Console.WriteLine(msg, classType.Name, property.Name);
    }
}

And the call is

WriteKeyProperty(typeof(Application));
WriteKeyProperty(typeof(Land));
Igal23
  • 122
  • 3
  • Is it possible that I do with Application and as Land and Alternative Properties will be there to get their primary key also. I am basically going to use the primary keys in an update function where I will have a function like public async Task Update(Application oldApplication, Application updatedApplication) and I will be using OldApplication to get all primary keys. – Tina Nov 03 '17 at 15:25
  • Do you need to get the real value of the oldApplication key or just the key property name from this class? You can do something like var properties = oldApplication.GetType().GetProperties(); and then use the above code to get the key property name – Igal23 Nov 03 '17 at 15:29
  • I am going to traverse through properties/values I have in oldApplication and i want to get keys like LandId and similarly want key for AlternateSigningAuthorities. The main goal is to use use those keys in linq query to make a generic function which will basically loop through all the values present in oldApplication and compare that with updatedApplication based on keys – Tina Nov 03 '17 at 16:14
0

No sure what u are trying to do. your first code:

var property = properties
                .FirstOrDefault(p => p.GetCustomAttributes(false)
                    .Any(a => a.GetType() == typeof(KeyAttribute)));

the property is PropertyInfo, therefore it gives you the name of the primary key. The a => a.GetType() == typeof(KeyAttribute) return the uniquely identifier of the class. So it is returning ApplicationId.

Your second code is not working because you are returning name of the CustomAttribute which is a object type.

I think your first code should work for all 3 classes.

Shuvra
  • 199
  • 11
  • Actually through my first code I am getting ApplicationId which is fine but then I want to loop through other properties from the same code and want to get LandID and key from AlternateSigningAuthority. I have a function public async Task Update(Application oldApplication, Application updatedApplication) and I am going to loop through oldApplication and with try to get all keys and will be using them to compare with UpdatedApplication in generic function. So I am trying to get all keys through Application. – Tina Nov 03 '17 at 16:21