gpt4 book ai didi

c# - 没有泛型方法 'ThenBy'

转载 作者:行者123 更新时间:2023-11-30 21:29:32 25 4
gpt4 key购买 nike

我正在尝试添加 ThenById() 方法,该方法将在调用 IOrderedQueryable 上的 OrderBy() 后启动:

public static IOrderedQueryable<TEntity> ThenById<TEntity>(this IQueryable<TEntity> source)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}

var command = "ThenBy";
var thenByProperty = "Id";
var type = typeof(TEntity);

if (type.GetProperty(thenByProperty) == null)
{
throw new MissingFieldException(nameof(thenByProperty));
}

var param = Expression.Parameter(type, "p");

var property = type.GetProperty(thenByProperty, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

var propertyAccess = Expression.MakeMemberAccess(param, property);
var orderByExpression = Expression.Lambda(propertyAccess, param);

var resultExpression = Expression.Call(
typeof(IOrderedQueryable),
command,
new Type[] { type, property.PropertyType },
source.Expression,
Expression.Quote(orderByExpression));
return (IOrderedQueryable<TEntity>)source.Provider.CreateQuery<TEntity>(resultExpression);
}

我收到以下错误消息:

No generic method 'ThenBy' on type 'System.Linq.IOrderedQueryable' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic.

最佳答案

ThenBy 扩展方法在 System.Linq.Queryable 类中,而不是在 IOrderedQueryable 中。您只需要在您的代码中替换它:

public static IOrderedQueryable<TEntity> ThenById<TEntity>(
this IOrderedQueryable<TEntity> source)
{
//snip

var resultExpression = Expression.Call(
typeof(System.Linq.Queryable),
command,
new Type[] { type, property.PropertyType },
source.Expression,
Expression.Quote(orderByExpression));
return (IOrderedQueryable<TEntity>)source.Provider.CreateQuery<TEntity>(resultExpression);
}

请注意,该方法应该扩展 IOrderedQueryable,而不仅仅是 IQueryable

但是,如果 TEntity 没有 Id 属性,这将在运行时失败。我的偏好是为所有具有 Id 属性的实体提供一个接口(interface),并在此处使用通用约束。这样你就可以完全避免表达式并获得编译时安全性。例如:

public interface IHasId
{
int Id { get; set; }
}

public class SomeEntity : IHasId
{
public int Id { get; set; }
public string Name { get; set; }
//etc
}

这简化了您的扩展方法:

public static IOrderedQueryable<TEntity> ThenById<TEntity>(
this IOrderedQueryable<TEntity> source)
where TEntity : IHasId
{
return source.ThenBy(e => e.Id);
}

关于c# - 没有泛型方法 'ThenBy',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55283329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com