c# - 如何获取主键

标签 c# reflection

我有一个模型

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

     }

还有一个模型

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

类似地,我有一个 AlternateSigningAuthority 模型。我想获得这些模型的主键。

我有适用于应用程序的代码

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

一旦我添加

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

我没有得到主键。我想使用应用程序模型来获取其他模型的 key 。

最佳答案

您只需要调用 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);
            }
        }

我引用了这个链接 Get [key] property from ViewModel

关于c# - 如何获取主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47098782/

相关文章:

c# - 翻译 DataGrid MouseEvent 所以我在 View 的代码隐藏中没有代码

c# - 模型的动态属性

c# - 为什么 HttpClient 不允许自动重定向?

java - 与 Class.forName() 松耦合

java - 通过反射/javassist调用不存在的函数

c# - 使用 ASP.net 打开与 MySQL 的连接

c# - 自动获取服务器IP给客户端

c# - 通过反射获取 Private Func<T> 成员

java - 在 driver=new ChromeDriver(); 行上获取 "InvocationTargetException"异常;

java - 使用反射修改抽象类中的字段