123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- namespace Fuel.Application
- {
- public class EntityHelper
- {
- public readonly IFreeSql _fsql;
- public EntityHelper(IFreeSql fsql)
- {
- _fsql = fsql;
- }
- /// <summary>
- /// 查询
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="predicate"></param>
- /// <returns></returns>
- public async Task<List<T>> GetEntitiesAsync<T>(Expression<Func<T, bool>> predicate) where T : class
- {
- try
- {
- // 查询满足条件的实体
- return await _fsql.Select<T>().Where(predicate).ToListAsync();
- }
- catch (Exception ex)
- {
- }
- return new List<T>();
- }
- /// <summary>
- /// 插入
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="entity"></param>
- /// <returns></returns>
- public async Task<T> InsertEntityAsync<T>(T entity) where T : class
- {
- try
- {
- // 插入数据
- _fsql.Insert(entity).ExecuteAffrows();
- // 获取插入后的主键值
- object insertedIdObj = _fsql.Ado.ExecuteScalar("SELECT LAST_INSERT_ID();");
- int insertedId = Convert.ToInt32(insertedIdObj);
- // 查询插入后的数据
- return await GetInsertedEntityAsync<T>(insertedId);
- }
- catch (Exception ex)
- {
- }
- return null;
- }
- private async Task<T> GetInsertedEntityAsync<T>(int insertedId) where T : class
- {
- // 获取实体类型
- Type entityType = typeof(T);
- // 获取 Id 属性
- PropertyInfo idProperty = entityType.GetProperty("Id");
- if (idProperty == null)
- {
- throw new InvalidOperationException($"Entity type {entityType.Name} does not have an 'Id' property.");
- }
- // 构建查询条件
- var parameter = Expression.Parameter(entityType, "n");
- var propertyAccess = Expression.MakeMemberAccess(parameter, idProperty);
- var constantValue = Expression.Constant(insertedId, typeof(int));
- var equality = Expression.Equal(propertyAccess, constantValue);
- var lambda = Expression.Lambda<Func<T, bool>>(equality, parameter);
- // 查询插入后的数据
- return await _fsql.Select<T>().Where(lambda).FirstAsync();
- }
- /// <summary>
- /// 更新
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="entity"></param>
- /// <returns></returns>
- public async Task<bool> UpdateAsync<T>(T entity) where T : class
- {
- try
- {
- // 更新数据,显式指定类型参数 T
- int affectedRows = _fsql.Update<T>(entity).ExecuteAffrows();
- // 返回是否成功更新
- return affectedRows > 0;
- }
- catch (Exception ex)
- {
- // 可以在这里处理异常,例如日志记录
- // Console.WriteLine(ex.Message);
- }
- return false;
- }
- }
- }
|