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;
}
///
/// 查询
///
///
///
///
public async Task> GetEntitiesAsync(Expression> predicate) where T : class
{
try
{
// 查询满足条件的实体
return await _fsql.Select().Where(predicate).ToListAsync();
}
catch (Exception ex)
{
}
return new List();
}
///
/// 插入
///
///
///
///
public async Task InsertEntityAsync(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(insertedId);
}
catch (Exception ex)
{
}
return null;
}
private async Task GetInsertedEntityAsync(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>(equality, parameter);
// 查询插入后的数据
return await _fsql.Select().Where(lambda).FirstAsync();
}
///
/// 更新
///
///
///
///
public async Task UpdateAsync(T entity) where T : class
{
try
{
// 更新数据,显式指定类型参数 T
int affectedRows = _fsql.Update(entity).ExecuteAffrows();
// 返回是否成功更新
return affectedRows > 0;
}
catch (Exception ex)
{
// 可以在这里处理异常,例如日志记录
// Console.WriteLine(ex.Message);
}
return false;
}
}
}