c# 利用反射获取表主键并设置值
作者:互联网
private void SetTablePrimaryKey<T>(T entity) { PropertyInfo pkProp = typeof(T).GetProperties().Where(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Length >0).FirstOrDefault(); //主键名称 var keyName = pkProp.Name; //实体类中主键的值 //var keyId = pkProp.GetValue(entity).ToString(); foreach (PropertyInfo p in entity.GetType().GetProperties()) { if (p.Name.ToString() == keyName) { p.SetValue(entity, Guid.NewGuid().ToString(),null); } } }
实体类中的ID要加KeyAttribute
public class InterfaceVoyage : BaseEntity { [KeyAttribute] public string Id { get; set; } }View Code
标签:反射,pkProp,c#,entity,keyName,ToString,KeyAttribute,主键 来源: https://www.cnblogs.com/zy28/p/11428002.html