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; } }
本文介绍了一个通用方法,用于在实体类中自动设置主键值。通过反射获取带有KeyAttribute特性的属性,并将其值设为新的Guid字符串。示例中使用了InterfaceVoyage实体类进行演示。
773

被折叠的 条评论
为什么被折叠?



