C#利用反射获取实体类的主键名称或者获取实体类的值


 

//获取主键的 PropertyInfo
PropertyInfo pkProp = typeof(T).GetProperties().Where(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Length >0).FirstOrDefault();
//主键名称
var keyName=pkProp.Name;
//实体类中主键的值
 var keyId = pkProp.GetValue(model).ToString();

例如:

public WorkIDStatusViewModel GetWorkIDStatusEntity<T>(string resourcesCode, IEnumerable<t_Work> work, T model)
        {
            PropertyInfo pkProp = typeof(T).GetProperties().Where(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Length >0).FirstOrDefault();
            var resourcesId = pkProp.GetValue(model).ToString();

            var entity = work.Where(r => r.ResourcesCode == resourcesCode && r.ResourcesId == resourcesId).OrderByDescending(r => r.CreateDate).Select(s => new WorkIDStatusViewModel { WorkId = s.WorkId, Status = s.Status }).FirstOrDefault();
            if (entity != null)
                return new WorkIDStatusViewModel { WorkId = entity.WorkId, Status = entity.Status };
            else
                return new WorkIDStatusViewModel { WorkId = "", Status = -1 };
        }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM