using System; using System.Reflection; using Microsoft.EntityFrameworkCore; using System.Text; publicstaticclassFunction { ///<summary> /// 组合出获取RowNumber的SQL语句 ///</summary> ///<typeparam name="T">实体类</typeparam> ///<param name="value"></param> ///<param name="orderBy">排序字符串,e.g. "UpdateTime DESC, Id DESC"</param> ///<returns></returns> publicstaticIQueryable<T> GetPropertyToSql<T>(this DbSet<T> value, string orderBy = "Id DESC") where T : class { var type = value.GetType().GenericTypeArguments[0]; var builder = new StringBuilder(""); foreach (var property in type.GetProperties()) { if (property.PropertyType.IsPrimitive || property.PropertyType.IsEnum || !property.PropertyType.IsClass || property.PropertyType.Name == "String") { builder.Append(property.Name + ","); } } var properties = builder.Replace(",RowNumber", "").ToString().TrimEnd(','); var sql = string.Format("SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY {0}) AS RowNumber, {1} FROM {2}) temp", orderBy, properties, type.Name); returnvalue.FromSqlRaw(sql); }