C#获取实体类字段信息PropertyInfo,字段名称,字段值,字段属性标签

引用空间:
System.Reflection.PropertyInfo

 AnUser anUser = new AnUser();
            anUser.Id = "514f275979f64531b7fbbb2f89c8af49";
            anUser.UserNo = "5566110";
            PropertyInfo[] props = typeof(AnUser).GetProperties();//实体的字段列表
            foreach (var item in props)
            {
                //item.Name 获取字段名称
                if (item.Name == "Id")
                {
                   string id =  item.GetValue(anUser) as string;//获取字段值
                }
                var kkkk = item.Attributes;
                var kkkk2 = item.CustomAttributes;//自定义的属性标签
           
                //获取字段是否有[Key]属性标签
                bool isHave = kkkk2.Any(x => x.AttributeType == typeof(System.ComponentModel.DataAnnotations.KeyAttribute));
            }
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ayy.Models
{
    /// <summary>
    /// 用户
    /// </summary>
    [Table("AnUser")]
    public class AnUser
    { 
 
	    /// <summary>
        /// guid主键
        /// </summary>
        [Key]
        public string Id { set; get; }
		
        /// <summary>
        /// 工号
        /// </summary>
        public string UserNo { get; set; }
 
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章