/// <summary> /// 传入一个 dto 对象插入数据。dto 需要与实体建立映射关系,否则会报错 /// </summary> /// <typeparam name="TEntity"></typeparam> /// <typeparam name="TDto"></typeparam> /// <param name="dbContext"></param> /// <param name="dto"></param> /// <returns></returns> public static TEntity InsertFromDto <TEntity, TDto>(this IDbContext dbContext, TDto dto) { /* * 支持自动设置 主键=guid * 支持自动设置 CreationTime=DateTime.Now * 支持自动设置 IsDeleted=false */ Utils.CheckNull(dto); TEntity entity = MrcMapper.Map <TEntity>(dto); Type entityType = typeof(TEntity); TypeDescriptor typeDescriptor = TypeDescriptor.GetDescriptor(entityType); /* 设置 主键=guid */ if (typeDescriptor.PrimaryKeys.Count < 2) /* 只有无主键或单一主键的时候 */ { MappingMemberDescriptor primaryKeyDescriptor = typeDescriptor.PrimaryKeys.FirstOrDefault(); if (primaryKeyDescriptor != null && primaryKeyDescriptor.IsAutoIncrement == false) { var keyValue = primaryKeyDescriptor.GetValue(entity); if (keyValue.IsDefaultValueOfType(primaryKeyDescriptor.MemberInfoType) || string.Empty.Equals(keyValue)) { /* 如果未设置主键值,则自动设置为 guid */ if (primaryKeyDescriptor.MemberInfoType == typeof(string)) { primaryKeyDescriptor.SetValue(entity, IdHelper.CreateSnowflakeId().ToString()); } else if (primaryKeyDescriptor.MemberInfoType.GetUnderlyingType() == typeof(Guid)) { primaryKeyDescriptor.SetValue(entity, Guid.NewGuid()); } } } } /* 设置 CreationTime=DateTime.Now */ SetValueIfNeeded(entity, typeDescriptor, "CreationTime", DateTime.Now); /* 设置 IsDeleted=false */ SetValueIfNeeded(entity, typeDescriptor, "IsDeleted", false); return(dbContext.Insert(entity)); }