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