c# 利用反射获取表主键并设置值

核能气质少年 提交于 2019-11-28 21:49:09
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

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!