vendredi 3 novembre 2017

How to get primary keys

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.





Aucun commentaire:

Enregistrer un commentaire