c # using Reflected acquired primary key and sets the value

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

}
}

  Entity class ID to add KeyAttribute

public class InterfaceVoyage : BaseEntity
{
    [KeyAttribute]
    public string Id { get; set; }
}
View Code

 

Guess you like

Origin www.cnblogs.com/zy28/p/11428002.html